本文介绍了如何找到包含方括号的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用正则表达式在文本中搜索一堆关键字.
i'm using a regular expression to search for a bunch of keywords in a text.
找到所有关键字,但只有一个:[DAM]柏林.我知道它包含一个方括号,所以我逃脱了,但是仍然没有运气.我在做什么错了?
All keywords are found but one: [DAM]Berlin. I know it contains a square bracket so i escaped it, but still, no luck. What am i doing wrong?
这是我的php代码.
要搜索的关键字的文本:
The text to search for keywords:
$textToSearch= '<p><br>
Time ¦ emit LAb[au] <br>
<br>
[DAM]Berlin gallery<br>
<br>
Exhibition: February 21st - March 28th, 2009 <br>
<br>
Opening: Friday, February 20th, 2009 7-9 pm <br>';
正则表达式:
$find='/(?![^<]+>)\b(generative art console|Game of Life|framework notations|framework|Floating numbers|factorial|f5x5x3|f5x5x1|eversion|A-plus|16n|\[DAM\]Berlin gallery)\b/s';
替换回调函数:
function replaceCallback( $match )
{
if ( is_array( $match ) )
{
$htmlVersion = htmlspecialchars( $match[1], ENT_COMPAT, 'UTF-8' );
$urlVersion = urlencode( $match[1] );
return '<a class="tag" rel="tag-definition" title="Click to know more about ' . $htmlVersion . '" href="?tag=' . $urlVersion. '">'. $htmlVersion . '</a>';
}
return $match;
}
最后是电话:
$tagged_content = preg_replace_callback($find, 'replaceCallback', $textToSearch);
谢谢您的帮助!
推荐答案
我认为这是因为[
不是文字字符",所以\b[
在[ >.您可能需要将正则表达式更改为:
I think it's because [
isn't a "word character", so \b[
can't match [
in the beginning of [DAM]Berlin
. You probably need to change your regex to:
$find='/(?![^<]+>)(\b(?:generative art console|Game of Life|framework notations|framework|Floating numbers|factorial|f5x5x3|f5x5x1|eversion|A-plus|16n)|\[DAM\]Berlin gallery)\b/s';
来自丹尼尔·詹姆斯(Daniel James)的评论:
From Daniel James's comment:
$find='/(?![^<]+>)(?<!\w)(generative art console|Game of Life|framework notations|framework|Floating numbers|factorial|f5x5x3|f5x5x1|eversion|A-plus|16n|\[DAM\]Berlin gallery)\b/s';
这篇关于如何找到包含方括号的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!