PHP preg_replace url 字符串

标签 php preg-replace

好的,我有一个 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/

相关文章:

php - HTML 表的并行 MySQL 查询 - WHILE(x 或 y)?

javascript - 将 PHP preg_replace 转换为 javascript 并将其设置为递归

php - 正则表达式 - preg_replace php - 理解

php - preg_replace() 替换第二次出现

php - 返回 Php 的 eval 函数

javascript - 通过 Javascript 将 PHP 数组传递给另一个 PHP 脚本

php - Ubuntu 中这些参数的等价物是什么?

mysql - 如何在 mysql match() against () 中使用 preg_replace() 函数

regex - 似乎无法为 URL 垃圾邮件删除程序找到可靠的正则表达式

php - 将 json 解码为 php 数组,然后解码为 mysql