PHP正则表达式preg_替换括号之间的多个值
我正在尝试使用正则表达式搜索字符串,替换几个值并构建URL。我以前从未使用过正则表达式(从头开始),所以有点卡住了 字符串作为标识符包含在[方括号]中。我尝试了多种方法-我不知道如何构造正则表达式或preg_replace方法,以便能够执行多个替换,理想情况下没有大量重复的正则表达式行,但这正是我尝试的方向:PHP正则表达式preg_替换括号之间的多个值,php,regex,string,replace,preg-replace,Php,Regex,String,Replace,Preg Replace,我正在尝试使用正则表达式搜索字符串,替换几个值并构建URL。我以前从未使用过正则表达式(从头开始),所以有点卡住了 字符串作为标识符包含在[方括号]中。我尝试了多种方法-我不知道如何构造正则表达式或preg_replace方法,以便能够执行多个替换,理想情况下没有大量重复的正则表达式行,但这正是我尝试的方向: $string= '[mycode="gallery" type="single" id="1" data="only"]'; //INPUT $string = pre
$string= '[mycode="gallery" type="single" id="1" data="only"]'; //INPUT
$string = preg_replace('/\mycode="(.*)"\]/', '$1/mycode"', $string);
$string = preg_replace('/\type="(.*)"\]/', 'mycode_$1.php', $string);
$string = preg_replace('/\id="(.*)"\]/', '?id=$1', $string);
$string = preg_replace('/\data="(.*)"\]/', '&data=$1', $string);
最终输出:
gallery/\u mycode\u single.php?id=1&data=only(同时删除[])
我知道这目前不起作用,因为我不知道从多行编译输出的方法;任何协助都将不胜感激。谢谢 您需要进行两层操作,首先在
[]
之间提取所有内容,然后根据需要替换这些值。您可以使用preg\u replace\u回调
要做到这一点
$string= '[mycode="gallery" type="single" id="1" data="only"]';
echo preg_replace_callback('/\[([^\]]+)\]/', function($match) {
$string = preg_replace('/\h*mycode="([^"]+)"\h*/', '$1/mycode', $match[1]);
$string = preg_replace('/\h*type="([^"]+)"\h*/', 'mycode_$1.php', $string);
$string = preg_replace('/\h*id="([^"]+)"\h*/', '?id=$1', $string);
$string = preg_replace('/\h*data="([^"]+)"\h*/', '&data=$1', $string);
return $string;
}, $string);
由于以下几个原因,您的正则表达式不起作用:
]
\d
是一个数字\t
是一个选项卡演示:您需要进入两层,首先在
[]
之间拉取所有内容,然后根据需要替换这些值。您可以使用preg\u replace\u回调
要做到这一点
$string= '[mycode="gallery" type="single" id="1" data="only"]';
echo preg_replace_callback('/\[([^\]]+)\]/', function($match) {
$string = preg_replace('/\h*mycode="([^"]+)"\h*/', '$1/mycode', $match[1]);
$string = preg_replace('/\h*type="([^"]+)"\h*/', 'mycode_$1.php', $string);
$string = preg_replace('/\h*id="([^"]+)"\h*/', '?id=$1', $string);
$string = preg_replace('/\h*data="([^"]+)"\h*/', '&data=$1', $string);
return $string;
}, $string);
由于以下几个原因,您的正则表达式不起作用:
]
\d
是一个数字\t
是一个选项卡演示:对不起,是的-我想这是我之前工作中留下的一个打字错误。我以前没有用过preg_replace_回调-你能详细说明一下吗?我想你是想先用它来获取[]括号的内容,然后再做其他事情?使用你在下面提供的答案工作-再次感谢你,是的-我认为]是我之前工作中留下的一个打字错误。我以前没有用过preg_replace_回调-你能详细说明一下吗?我想你是想先用它来获取[]括号的内容,然后再做其他事情?使用下面提供的答案工作-再次感谢