// 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";
I need to write a preg_replace()
function which replace the value between "=
" + "&
" or in the case of the bottom string everything after "=" when & doesnt exi开发者_如何转开发st with "newAction"..
Does anyone have any ideas?
This is what I have tried so far, but failed:
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;
}
$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;
Output:
www.development_crs.php?action=newAction&test1&test2
try the pattern below
$pattern='/action=([a-z0-9_\-%]+)&/';
$pattern = '/action=.*?(&|$)/';
$replacement = "action=$action$1";
I can see a few problems with your pattern. Not that I'm a regex expert however,
Try something like this:
/action=[^&]+/
or
/action=[^&]*/
This will match 'action=' and then the rest of the string until it encounters a &. The + means that it must have at least one character between the = and the & to accept the string.
Hope this helps :)
精彩评论