A regular expression to match one that begins with

I am trying to get a match from this line

"Dial [Toll Free 1800 102 8880 ext: 246] to connect to the restaurant. <a class='tooltip' title='Foodiebay has now introduced value added calling features through the website. You just need to dial this number and we ..." 

Where I want to check if a variable starts with the line Type

 $a = 'Dial [Toll Free 1800 102 8880 ext: 246] to connect to the restaurant. <a class='tooltip' title='Foodiebay has now introduced value added calling features through the website. You just need to dial this number and we'; preg_match('/[^Dial]/', $a, $matches); 
+4
source share
2 answers

Lose square brackets:

 /^Dial / 

This corresponds to the "Dial " at the beginning of the line.

FYI: The original regular expression is an inverted character class [^...] that matches any character that does not belong to the class. In this case, it will match any character that is not "D", "i", "a" or "l". Since almost every line will have at least a character that is not one of them, almost every line will match.

+8
source

I prefer to use strpos instead of regexp:

 if (strpos($a, 'Dial') === 0) { // ... 

=== important as it can also return false. (false == 0) true, but (false === 0) is false.

Edit: after tests (a million iterations) with the OP string, strpos is about 30% faster than substr, which is about 50% faster than preg_match.

+5
source

All Articles