Regex find something in the middle of a string

I tried ^ name & this does not work, how can I find the name inside this line, I had it before, but no more :(? "hello-my-name-is"

+4
source share
3 answers

/.name./ Two dots indicate that there is at least one character on each side.

+2
source

I think you are looking for either /name/ or /\bname\b/ . \b is a word boundary indicator. See this document for more information: http://www.regular-expressions.info/wordboundaries.html

The reason ^name$ does not give you any results when searching for the string "hello-my-name-is" , because the ^ character binds the search to the beginning of the string. Similarly $ ties the search to the end. For instance:

  • ^name only works if the line starts with "name" , for example. "name is cool"
  • name$ only works if the line ends with "name" for example. "where is name"

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

+2
source

/name/ seems to work well here.

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

Output -

 hello-my-name-is => 1 

Means that it was found name subsctring, and it appeared 1 time.

0
source

All Articles