1

我整个早上都试图搜索这个答案,但没有运气,我想做的就是匹配 [幻灯片或 [图库与包含的 [ 括号..

代码如下。

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

我用过的正则表达式,我虽然会这样工作。搜索字符串的开头,使用 / 将避免 [ 被用作正则表达式的一部分并成为搜索的一部分,

正则表达式不是我的事..虽然我读得越多,它就变得更清晰了..

4

2 回答 2

7

The escape character is \ 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)
于 2010-01-14T13:10:01.273 回答
3
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. So you can do:

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

or

preg_match("|^\[slideshow|", $gallery)
于 2010-01-14T13:10:12.723 回答