Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to match someting that starts with

Tags:

regex

php

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);
like image 752
Harsha M V Avatar asked Nov 28 '10 03:11

Harsha M V


People also ask

Which regular expression will match the beginning of a string?

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.

How do I match a word in a regular expression?

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.

What does '$' mean in regex?

$ 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.

Which matches the start and end of the string?

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.


2 Answers

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.

like image 146
Marcelo Cantos Avatar answered Nov 03 '22 00:11

Marcelo Cantos


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.

like image 26
Vincent Savard Avatar answered Nov 02 '22 23:11

Vincent Savard