Reputation: 13
Hello I have html file I want to find word in matching position Like
Hello my name is jim. Hello my name is emma. hello my name is test.
What i want to do is echo word after my name is
and before .
(DOT) I have this php function But it will just echo first name jim how i can loop
<?php
$data = file_get_contents("test.html");
$name = cut_str($data,'my name is ','.');
echo $name;
function cut_str($str, $left, $right){
$str = substr(stristr($str, $left), strlen($left));
$leftLen = strlen(stristr($str, $right));
$leftLen = $leftLen ? -($leftLen) : strlen($str);
$str = substr($str, 0, $leftLen);
return $str;
}
?>
Upvotes: 1
Views: 118
Reputation: 21422
You can use preg_match_all
as
preg_match_all('/(?<=(my name is))(.*?)(?=(\.))/i', 'Hello my name is jim. Hello my name is emma. hello my name is test.',$res);
print_r($res[0]);
Explanation
(?<=(my name is))
Positive Lookbehind - Capturing group (my name is)
my name is
matches the characters my name is
literally .*?
matches any character (except newline)(?=(\.))
Positive Lookahead - \.
matches the character .
literallyi modifier:
insensitive. Case insensitive match (ignores case of [a-zA-Z])
Or you can also use it as
preg_match_all('/my\sname\sis(.*?)\./i', 'Hello my name is jim. Hello my name is emma. hello my name is test.',$res);
print_r($res[1]);
Upvotes: 0
Reputation: 23880
This should do it.
$name = preg_match_all('~My name is (.+?)\.~', $data, $names);
print_r($names[1]);
The .
is any character.
The +
is one or more characters.
The ?
stops the matching at the first .
.
The ~
are delimiters telling the regex where to stop and start.
PHP Demo: https://eval.in/418218
Regex101 Demo: https://regex101.com/r/dO8mQ4/1
Depending on how loose or strict you want it you may need modifiers.
You could do
$name = preg_match_all('~My\s+name\s+is\s+(.+?)\.~i', $data, $names);
print_r($names[1]);
This allows one or more whitespace (tab, newline, space) (\s+) between each word and makes the words case insensitive(i
after delimiter).
Upvotes: 1