简体   繁体   中英

Regular Expression to match someting that starts with

I am trying to get a Match from this string

"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 string Dial

$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);

Lose the square brackets:

/^Dial /

This matches the string "Dial " at the start of a line.

FYI: Your original regex is an inverted character class [^...] , which matches any character that isn't in the class. In this case, it will match any character that isn't 'D', 'i', 'a' or 'l'. Since almost every line will have at least character that isn't one of those, almost every line will match.

I'd rather to use strpos instead of a regexp :

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

=== is important, because it could also returns false. (false == 0) is true, but (false === 0) is false.

Edit: After tests (one million iterations) with OP's string, strpos is about 30% faster than substr, which is about 50% faster than preg_match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM