我有正则表达式
eregi_replace("s=.*&","",$section->urlToThreads);
它的作用是用''
替换所有内容,该内容以's='
开头,以'&'
我想做的也是“&”在's ='后直到字符串结尾才找到,然后用''
替换's ='到字符串结尾的所有内容E.g。
test.php?s = 12232dsd23423& t = 41 会变成 test.php?t = 41
和
test.php?t = 41& s = 12232dsd23423 会变成 test.php?t = 41
答案 0 :(得分:3)
您可以将&
设为可选,并且仅允许非&
字符匹配。另外,使用单词边界只匹配s=
(而不是links=
的子字符串):
"\bs=[^&]*&?"
但你不应该再使用ereg
了。更新至preg
:
$result = preg_replace('/\bs=[^&]*&?/', '', $section->urlToThreads);
答案 1 :(得分:2)
解决方案 - 没有REGEX
$str = $section->urlToThreads;
$url = '';
$url = $section->urlToThreads;
$pos = strpos( $str,'s=');
if ($pos)
{
$pos_ampersand = strpos( $str,'&',$pos);
if ($pos_ampersand) //if ampersand is found after s=
{
$url = substr($str, 0, $pos) . substr($str, $pos_ampersand+1, strlen($str));
}
else // if no ampersand found after s=
{
$url = substr($str, 0, $pos-1);
}
}
$section->urlToThreads = $url;
答案 2 :(得分:1)
如果是preg_replace我会这样做:
preg_replace('@(\?)s(=[^&]*)?&?|&s(=[^&]*)?@', '\\1', $section->urlToThreads);
一些测试:
$tests = array(
'test.php?s',
'test.php?s=1',
'test.php?as=1',
'test.php?s&as=1',
'test.php?s=1&as=1',
'test.php?as=1&s',
'test.php?as=1&s=1',
'test.php?as=1&s&bs=1',
'test.php?as=1&s=1&bs=1'
);
foreach($tests as $test){
echo sprintf("%-22s -> %-22s\n", $test, preg_replace('@(\?)s(=[^&]*)?&?|&s(=[^&]*)?@', '\\1', $test));
}
输出:
test.php?s -> test.php?
test.php?s=1 -> test.php?
test.php?as=1 -> test.php?as=1
test.php?s&as=1 -> test.php?as=1
test.php?s=1&as=1 -> test.php?as=1
test.php?as=1&s -> test.php?as=1
test.php?as=1&s=1 -> test.php?as=1
test.php?as=1&s&bs=1 -> test.php?as=1&bs=1
test.php?as=1&s=1&bs=1 -> test.php?as=1&bs=1
答案 3 :(得分:0)
s=.*(?:&|$)
检查&
或行/字符串的结尾。