I've tried ^name&
but it does not work. How can I find a 开发者_开发问答name inside hello-my-name-is
/.name./
The two points indicate, that there is at least one character on each side.
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
/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.
精彩评论