2016-11-18 46 views
1

我需要把像user-profile/id=3这样的字符串转换为正则表单。我试过'user-profile/id=\d+$''user-profile/([a-z][.][0-9]+)/?$',但他们都没有工作。什么是正确的方法?WordPress的正则表达式不能按预期工作

+0

你想从得到什么这个字符串与正则表达式? –

+0

我只想提取'id = 3'部分。 –

+0

在这种情况下,我希望我的回答能帮助你。 –

回答

1

由于你的字符串是alw ays的格式如上,你不需要一个正则表达式。用区区explode

explode("/", $s)[1] 

this demo

另一个非正则表达式的方法:使用strstr后,包括/得到子,然后拿到substr从1吨焦炭荷兰国际集团:

substr(strstr($s, "/"),1); 

another PHP demo

+0

如果我的答案对您有帮助,请考虑upvoting(请参阅[如何在堆栈溢出上注册?](http://meta.stackexchange.com/问题/ 173399 /如何对给予好评,对堆栈溢出))。 –

1

你的问题是,你不是逃避/字符反斜杠。

解决该问题后可能会遇到的另一个问题是您正在使用$字符,这意味着行尾。如果之后有更多的字符,即使只有一个空格,那么它也不会匹配。

如果你尝试:

user-profile\/(id=\d+) 

你可能会发现,它匹配得很好。我添加的括号将在捕获组#1中捕获id=3

+0

没有必要在正则表达式中转义'/'。尝试''〜用户配置文件/(id = \ d +)〜'' –

0

如果你只是想提取id=3我建议使用preg_replace。像:

$str = 'user-profile/id=3'; 
$after_preg = preg_replace('/user-profile\//', '', $str); 
echo $after_preg; 

如果你想获得只是一个数字就可以如下:

$str = 'user-profile/id=3'; 
$after_preg = preg_replace('/user-profile\/id=/', '', $str); 
echo $after_preg; 

更多关于它,你可以在PHP Manual: preg_replace

阅读如果你想检查是否字符串就像user-profile/id=3你可以用正则表达式:

user-profile\/id=\d* 
相关问题