2015-10-15 92 views
0

我想查找一个特殊的单词,在一个字符串中使用preg_match,并在它后面回显100个字符。
为此,我需要知道preg_match()已找到的单词的位置。如何知道preg_match找到的单词的位置

也许你会建议我使用strpos()寻找它的位置,但与strpos()问题是例如,当我的“艺术”之前在我的字符串“智能”和“艺术”和“智能”来了两个词, strpos发现“聪明”,而我希望它找到“艺术”。这就是为什么我决定使用preg_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 .' ; 
    ?> 
+2

也许使用'PREG_OFFSET_CAPTURE'标志? [PHP文档](http://www.php.net/manual/en/function.preg-match.php) –

回答

0

试试这个一到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]) 
?> 

输出:

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 
+0

非常感谢! –