2015-10-15 49 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

非常感謝! –

相關問題