正则表达式匹配一个确切的字符串

时间:2013-02-11 18:48:38

标签: php regex string preg-match

使用php,匹配精确字符串的正则表达式是什么。

说我们有文字:

Hello, world. 

How are you today?

Today is sunshine and snow wouldn't you know.

我如何使用正则表达式匹配字符串?:

sunshine and snow

1 个答案:

答案 0 :(得分:2)

使用preg_match:

<?php
// The "i" after the pattern delimiter indicates a case-insensitive search
if (preg_match("/php/i", "PHP is the web scripting language of choice.")) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}
?>

使用strpos:

<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'";
} else {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
}
?>