2013-02-11 71 views
0

使用PHP,什么是正则表达式匹配一个确切的字符串。正则表达式匹配一个确切的字符串

说我们有文字:

Hello, world. 

How are you today? 

Today is sunshine and snow wouldn't you know. 

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

sunshine and snow 
+4

不要对正确的字符串使用正则表达式,而是使用“strpos”。 – gpojd 2013-02-11 18:50:23

+0

如果你有确切的字符串,你可以使用strstr或stristr(不区分大小写) – nhahtdh 2013-02-11 18:50:26

+0

如果没有元字符,你也可以在正则表达式中注意一个字符串。 – mario 2013-02-11 18:52:29

回答

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"; 
} 
?> 
相关问题