我有一个这样的正则表达式
eregi_replace("s=.*&","",$section->urlToThreads);
它所做的是用''
替换所有内容,以's='
开头,以'&'
结尾
我还想做的是,如果在"s="之后直到字符串末尾找不到"&",则将从"s="到字符串末尾的所有内容替换为">
例如
test.php?s=12232dsd23423&t=41 将变为 test.php?t=41
和
test.php?t=41&s=12232dsd23423 将变为 test.php?t=41
您可以将
&
设置为可选,并仅允许非&
字符在两者之间匹配。此外,使用单词边界,以便仅匹配s=
(而不是 links=
的子字符串(:
"'bs=[^&]*&?"
但是你不应该再使用ereg
了。更新到preg
:
$result = preg_replace('/'bs=[^&]*&?/', '', $section->urlToThreads);
解决方案 - 没有正则表达式
$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;
如果是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
>s=.*(?:&|$)
检查行/字符串的&
或结尾。