Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP预替换修改_Php_Regex_Preg Replace - Fatal编程技术网

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>