[英]PHP preg_replace
I have to do the following with preg_replace in PHP: 我必须在PHP中使用preg_replace进行以下操作:
[some text][id]
should be replaced by <a href='id'>some_text</a>
where id
is an integer [some text][id]
应该替换为<a href='id'>some_text</a>
,其中id
是整数
Tried the following, unfortunately didn't work as expected: 尝试了以下操作,很遗憾未能按预期方式工作:
preg_replace("/\[[^)]\]\[[0-9]+\]/","<a href='$2'>$1</a>",$string);
Also, an example [some text]][id]
with extra bracket may be considered, where the last bracket should be taken. 另外,可以考虑带有额外括号的示例
[some text]][id]
,该括号应放在最后一个括号中。
Any ideas? 有任何想法吗?
Here's a solution: 这是一个解决方案:
$string = '[some text][117]';
$s = preg_replace("/\[([^\]]+)\]\[([0-9]+)\]/","<a href='$2'>$1</a>",$string);
var_dump($s);
First - to use $1
(or $2
) you need to capture pattern in brackets ()
. 首先使用
$1
(或$2
),您需要在方括号()
捕获模式。
Second mistake - you're trying to find ^)
, but you don't have )
in your text. 第二个错误-您尝试查找
^)
,但您的文本中没有)
。 So I replaced )
to ]
. 因此我将
)
替换为]
。
Update for an extra ]
: 额外更新
]
:
$s = preg_replace("/\[([^\]]+)(\]?)\]\[([0-9]+)\]/","<a href='$3'>$1$2</a>",$string);
Not sure what you need to do with this founded ]
, so I added it to a link text. 不知道您需要使用这个已建立的
]
做什么,所以我将其添加到链接文本中。
In case of a lot of ]]]
you can use: 如果有很多
]]]
,则可以使用:
$s = preg_replace("/\[([^\]]+)(\]*)\]\[([0-9]+)\]/","<a href='$3'>$1$2</a>",$string);
\[(\D+)\]\[(\d+)\]
\\D - Any non-digit \\d - Any digit \\ D-任何非数字\\ d-任何数字
Test it here: http://www.phpliveregex.com/p/k4X 在此处进行测试: http : //www.phpliveregex.com/p/k4X
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.