2013-02-11 6 views
0

En utilisant php, quelle est la regex pour correspondre à une chaîne exacte.regex pour correspondre à une chaîne exacte

Disons que nous avons le texte:

Hello, world. 

How are you today? 

Today is sunshine and snow wouldn't you know. 

Comment puis-je utiliser regex pour correspondre à la chaîne ?:

sunshine and snow 
+4

N'utilisez pas une regex pour les chaînes exactes, utilisez plutôt "strpos". – gpojd

+0

Si vous avez une chaîne exacte, vous pouvez utiliser strstr ou stristr (insensible à la casse) – nhahtdh

+0

Et vous pourriez aussi juste noter une chaîne littérale dans une regex, s'il n'y a pas de méta-caractères dedans. – mario

Répondre

2

En utilisant 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."; 
} 
?> 

Utilisation 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"; 
} 
?> 
Questions connexes