好的,我有一个 preg_replace 语句来替换 url 字符串。 第一个和第二个变量工作,但我需要第二个字符串子的帮助....
$html = str_replace('index.php','index',$html);
$html = preg_replace('/index\?cat=([a-z0-9]+)/i','index/$1',$html);
$html = preg_replace('/index\?cat=([a-z0-9]+)/&sub=([a-z0-9]+)/i','index/$1/$2',$html);
最佳答案
假设$html
包含:
index.php?cat=123&sub=456
在 str_replace
$html 变为:
index?cat=123&sub=456
在第一个 preg_replace 之后:
index/123&sub=456
那么第二个 preg_replace 不匹配。
你最好修改一下preg_replace的顺序:
//$html -> index.php?cat=123&sub=456
$html = str_replace('index.php','index',$html);
//$html -> index?cat=123&sub=456
$html = preg_replace('/index\?cat=([a-z0-9]+)&sub=([a-z0-9]+)/i','index/$1/$2',$html);
//$html -> index/123/456
$html = preg_replace('/index\?cat=([a-z0-9]+)/i','index/$1',$html);
//$html -> index/123/456
关于PHP preg_replace url 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21649482/