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);
The meta character “^” matches the beginning of a particular string i.e. it matches the first character of the string. For example, The expression “^\d” matches the string/line starting with a digit. The expression “^[a-z]” matches the string/line starting with a lower case alphabet.
To run a “whole words only” search using a regular expression, simply place the word between two word boundaries, as we did with ‹ \bcat\b ›. The first ‹ \b › requires the ‹ c › to occur at the very start of the string, or after a nonword character.
$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.
Explanation: '^' (carat) matches the start of the string. '$' (dollar sign) matches the end of the string. Sanfoundry Certification Contest of the Month is Live. 100+ Subjects.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With