PHP preg_replace
PHP preg_replace
我必须在 PHP 中使用 preg_replace 执行以下操作:
[some text][id]
应替换为 <a href='id'>some_text</a>
其中 id
是整数
尝试了以下方法,不幸的是没有按预期工作:
preg_replace("/\[[^)]\]\[[0-9]+\]/","<a href=''></a>",$string);
此外,可以考虑一个带有额外括号的示例 [some text]][id]
,其中应采用最后一个括号。
有什么想法吗?
这是一个解决方案:
$string = '[some text][117]';
$s = preg_replace("/\[([^\]]+)\]\[([0-9]+)\]/","<a href=''></a>",$string);
var_dump($s);
首先 - 要使用 </code>(或 <code>
),您需要在括号 ()
.
中捕获模式
第二个错误 - 您试图查找 ^)
,但您的文本中没有 )
。所以我将 )
替换为 ]
.
更新 额外 ]
:
$s = preg_replace("/\[([^\]]+)(\]?)\]\[([0-9]+)\]/","<a href=''></a>",$string);
不知道你需要用这个创建的 ]
做什么,所以我把它添加到 link 文本中。
如果有很多 ]]]
你可以使用:
$s = preg_replace("/\[([^\]]+)(\]*)\]\[([0-9]+)\]/","<a href=''></a>",$string);
\[(\D+)\]\[(\d+)\]
\D - 任何非数字
\d - 任何数字
我必须在 PHP 中使用 preg_replace 执行以下操作:
[some text][id]
应替换为 <a href='id'>some_text</a>
其中 id
是整数
尝试了以下方法,不幸的是没有按预期工作:
preg_replace("/\[[^)]\]\[[0-9]+\]/","<a href=''></a>",$string);
此外,可以考虑一个带有额外括号的示例 [some text]][id]
,其中应采用最后一个括号。
有什么想法吗?
这是一个解决方案:
$string = '[some text][117]';
$s = preg_replace("/\[([^\]]+)\]\[([0-9]+)\]/","<a href=''></a>",$string);
var_dump($s);
首先 - 要使用 </code>(或 <code>
),您需要在括号 ()
.
第二个错误 - 您试图查找 ^)
,但您的文本中没有 )
。所以我将 )
替换为 ]
.
更新 额外 ]
:
$s = preg_replace("/\[([^\]]+)(\]?)\]\[([0-9]+)\]/","<a href=''></a>",$string);
不知道你需要用这个创建的 ]
做什么,所以我把它添加到 link 文本中。
如果有很多 ]]]
你可以使用:
$s = preg_replace("/\[([^\]]+)(\]*)\]\[([0-9]+)\]/","<a href=''></a>",$string);
\[(\D+)\]\[(\d+)\]
\D - 任何非数字 \d - 任何数字