简体   繁体   English

PHP正则表达式,如何匹配包含[符号的第一部分?

[英]PHP Regular expression, how to match the first section which includes a [ symbol?

I've tried to search for this answer all morning, but with no luck, all i want to do is match [slideshow or [gallery with the included [ bracket.. 我试图整个上午都在寻找这个答案,但是没有运气,我只想匹配[幻灯片或带有[括号的画廊]。

code as follows. 代码如下。

$gallery = get_post_meta($post->ID, 'gallery', true);


if (preg_match("|^/[slideshow", $gallery)) {
    echo "Slideshow was forund";
} else if (preg_match("|^/[nggallery", $gallery)) {
   echo "Gallery was found";
} else {
   echo "No Match found - No Meta Data available"; 
}

The regular expression I've used, I though would work like this. 我使用过的正则表达式虽然可以这样工作。 search the start of the string, and using / would escape the [ from being used as part of the regular expression and be part of the search, 搜索字符串的开头,然后使用/将[排除为正则表达式的一部分而成为搜索的一部分,

regular expressions is just not my thing.... although the more reading i do, it becomes a little more clearer.. 正则表达式不是我的事。。。尽管我读得更多,但变得更加清晰。

The escape character is \\ not / . 转义字符为\\ not / Furthermore, you need to end the regex with the same delimiter as at the start of the regex. 此外,您需要使用与正则表达式开始处相同的定界符结束该正则表达式。 So your code will need to be something like this: 因此,您的代码将需要是这样的:

preg_match("|^\[slideshow|", $gallery)
if (preg_match("/^\[slideshow/", $gallery)) {
    echo "Slideshow was forund";
} else if (preg_match("/^\[nggallery/", $gallery)) {
   echo "Gallery was found";
} else {
   echo "No Match found - No Meta Data available"; 
}

Changes made: 所做的更改:

The [ needs to be escaped as its a metachar, the escape char to be used is \\ . [需要作为其元字符进行转义,要使用的转义字符为\\ Also preg_match expects its first argument(regex) to be delimited between suitable char. 而且preg_match期望其第一个参数(regex)在合适的char之间定界。 So you can do: 因此,您可以执行以下操作:

preg_match("/^\[slideshow/", $gallery)

or 要么

preg_match("|^\[slideshow|", $gallery)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM