Php 如何知道preg_match找到的单词的位置
我想找到一个特殊的单词,在字符串中使用preg\u match,并回显它后面的100个字符。Php 如何知道preg_match找到的单词的位置,php,preg-match,Php,Preg Match,我想找到一个特殊的单词,在字符串中使用preg\u match,并回显它后面的100个字符。 为此,我需要知道preg_match()找到的单词的位置 也许你会建议我使用strpos()来找到它的位置,但是strpos()的问题是,例如,当我的字符串中有两个单词“smart”和“art”,并且“smart”在“art”之前,strpos找到“smart”,而我希望它找到“art”。这就是为什么我决定使用preg\u match() 以下代码是我编写的代码: <?php pattern =
为此,我需要知道
preg_match()
找到的单词的位置
也许你会建议我使用strpos()
来找到它的位置,但是strpos()
的问题是,例如,当我的字符串中有两个单词“smart”和“art”,并且“smart”在“art”之前,strpos找到“smart”,而我希望它找到“art”。这就是为什么我决定使用preg\u match()
以下代码是我编写的代码:
<?php pattern = "/\b' .$data[title]. '\b/i" ;
$article= $data['description'];
preg_match($pattern, $article, $matches); echo '. $matches .' ;
?>
例如:
<?php $pattern = "/\b' .art. '\b/i" ;
$article= "I didn’t think parents do not like that either…but son is so smart.who is studying art therapy";
preg_match($pattern, $article, $matches);
echo '. $art .' ;
?>
尝试使用此选项直接获取100个字符:
<?php
$pattern = "/\bart\b(.{100})/i";
$article= "I didn’t think parents do not like that either…but son is so smart.who is studying art therapy I didn’t think parents do not like that either…but son is so smart I didn’t think parents do not like that either…but son is so smart";
preg_match($pattern, $article, $matches);
print_r($matches);
echo 'Length: '+strlen($matches[1])
?>
是否可能使用
PREG\u OFFSET\u CAPTURE
标志?
Array
(
[0] => art therapy I didn’t think parents do not like that either…but son is so smart I didn’t think par
[1] => therapy I didn’t think parents do not like that either…but son is so smart I didn’t think par
)
Length: 100