AndyMaccarthur
AndyMaccarthur

Reputation: 51

Regex find word inside string

I've tried ^name& but it does not work. How can I find a name inside hello-my-name-is

Upvotes: 5

Views: 25870

Answers (3)

Ben
Ben

Reputation: 1392

I think what you're looking for is either /name/ or /\bname\b/. \b is an indicator for word boundary. See this doc for more info: http://www.regular-expressions.info/wordboundaries.html

The reason ^name$ doesn't give you any results when searching the string "hello-my-name-is" is because the character ^ anchors the search to the start of the string. Similarly $ anchors the search to the end. For example:

  • ^name works only if the string started with "name" e.g. "name is cool"
  • name$ works only if the string ended with "name" e.g. "where is name"

For more info about anchors see this page: http://www.regular-expressions.info/anchors.html

Upvotes: 4

Bibhas Debnath
Bibhas Debnath

Reputation: 14939

/name/ seems to work well here.

$str = "hello-my-name-is";
$str1 = preg_match("/name/", $str);
echo $str . " => " . $str1;

The output is -

hello-my-name-is => 1

Means it found the name subsctring, and it appeared 1 time.

Upvotes: 0

Florian
Florian

Reputation: 3171

/.name./ The two points indicate, that there is at least one character on each side.

Upvotes: 5

Related Questions