how to find a string containing a square bracket?

倖福魔咒の 提交于 2019-12-11 05:58:58

问题


i'm using a regular expression to search for a bunch of keywords in a text.

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?

here is my php code.

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>';

The regular expression:

$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';

the replace Callback function:

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;
}

and finally, the call:

$tagged_content = preg_replace_callback($find, 'replaceCallback',  $textToSearch);

Thank you for your help !


回答1:


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';

Edit: From Daniel James's comment:

This might be closer to the original intent, as it will still check that '[Dam]' doesn't follow a word character:

$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';



回答2:


The first section of your Regex is '/(?![^<]+>)\b' so wouldn't it only match "[DAM]Berlin gallery" if the character before it was a '>'?

try:

$find='/(?![^<]+>)\b(generative art console|Game of Life|framework notations|framework|Floating numbers|factorial|f5x5x3|f5x5x1|eversion|A-plus|16n|\[DAM\]Berlin gallery)\b/sm'

That adds the m modifier to your regex so that it will ignore new lines

http://www.phpro.org/tutorials/Introduction-to-PHP-Regex.html#8

"[the m modifier] treats a string as having only a single newline character at the end, even if there are multiple new lines in our string."



来源:https://stackoverflow.com/questions/1021591/how-to-find-a-string-containing-a-square-bracket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!