PHP预替换修改
我有一个表达式PHP预替换修改,php,regex,preg-replace,Php,Regex,Preg Replace,我有一个表达式[text][id],应该用链接 解决方案是(idis integer) 在这种情况下,应将其替换为 想法?使用函数的解决方案: $str = 'some text [hello][1] some text [there][2][news]'; // exemplary string $result = preg_replace_callback('/\[([^][]+)\]\[([^][]+)\](?:\[([^][]+)\])?/',function($m){ $c
[text][id]
,应该用链接
解决方案是(id
is integer)
在这种情况下,应将其替换为
想法?使用函数的解决方案:
$str = 'some text [hello][1] some text [there][2][news]'; // exemplary string
$result = preg_replace_callback('/\[([^][]+)\]\[([^][]+)\](?:\[([^][]+)\])?/',function($m){
$cls = (isset($m[3]))? " class='{$m[3]}'" : ""; // considering `class` attribute
return "<a href='{$m[2]}'$cls>{$m[1]}</a>";
},$str);
print_r($result);
$str='some text[hello][1]some text[there][2][news];//示范串
$result=preg\u replace\u回调('/\[([^][]+)\]\[([^][]+)\](?:\[([^][]+)\])?/,函数($m){
$cls=(isset($m[3])?“class='{$m[3]}'”:;//考虑`class`属性
返回“”;
}美元/平方米);
打印(结果);
输出(作为网页源代码):
一些文本一些文本
-考虑可选的第三个捕获组(用于类属性值)(?:\[([^][+)\])?
\[([0-9]+)\]
在做什么?或者id
是整数?是的,id是整数哪些是text
和type
?我想你需要2个正则表达式,因为每次替换都需要class=“$3”
,或者我想你可以在另一个步骤中去掉它,如果是空的。请参阅
[text][id][type]
$str = 'some text [hello][1] some text [there][2][news]'; // exemplary string
$result = preg_replace_callback('/\[([^][]+)\]\[([^][]+)\](?:\[([^][]+)\])?/',function($m){
$cls = (isset($m[3]))? " class='{$m[3]}'" : ""; // considering `class` attribute
return "<a href='{$m[2]}'$cls>{$m[1]}</a>";
},$str);
print_r($result);
some text <a href='1'>hello</a> some text <a href='2' class='news'>there</a>