// Below are a number of strings which need ammending
$string = "www.development_test.php?action=show_development_crs&test1&test2";
$string = "www.development_test.php?action=show_rfw&test1";
$string = "www.development_test.php?action=show_development_crs";
我需要编写一个preg_replace()
函数来替换“=
”+“&
”之间的值,或者在底部字符串的情况下替换“=”之后的所有内容,当&不存在“newAction”..
有没有人有任何想法?
这是我到目前为止所尝试过的,但失败了:
public function test1()
{
$action = "newAction";
$string = "www.development_crs.php?action=show_development_crs&test1&test2";
$pattern = '/(action=)(.*)(&)/';
$replacement = "action=$action&";
$string = preg_replace($pattern, $replacement, $string);
echo $string;
}
答案 0 :(得分:6)
$action = 'newAction';
$string = 'www.development_crs.php?action=show_development_crs&test1&test2';
$pattern = '/action=[^&]+(.*)/';
$replacement = "action=$action$1";
$string = preg_replace($pattern, $replacement, $string);
echo $string;
输出:
www.development_crs.php?action=newAction&test1&test2
答案 1 :(得分:3)
尝试下面的模式
$pattern='/action=([a-z0-9_\-%]+)&/';
答案 2 :(得分:0)
$pattern = '/action=.*?(&|$)/';
$replacement = "action=$action$1";
答案 3 :(得分:0)
我可以看到你的模式有一些问题。然而,并不是说我是一名正则表达式专家,
尝试这样的事情:
/动作= [^&安培;] + /
或
/动作= [^&安培;] * /
这将匹配'action ='然后匹配字符串的其余部分,直到它遇到&amp ;. +意味着它必须在=和&之间至少有一个字符。接受字符串。
希望这会有所帮助:)