2010-01-12 74 views
12

我想在大字符串中使用「關鍵字」。這些關鍵字開始和結束使用my_keyword並且是用戶定義的。如何在大字符串內搜索並查找兩個*字符之間的內容並返回每個實例?PHP:兩個字符之間的返回字符串

它可能會改變它的原因,部分關鍵字可以是用戶定義的,如page_date_Y這可能會顯示創建頁面的年份。

因此,我只需要搜索並返回這些*字符之間的內容。這是可能的,或者如果我不知道「關鍵字」長度或者我可能是什麼,是否有更好的方法來做到這一點?

+0

我發現了一個超級漂亮函數,它正是我想要的,但是,我希望把所有找到的關鍵字到一個數組。 http://www.justin-cook.com/wp/2006/03/31/php-parse-a-string-between-two-strings/有沒有人有關於如何修改該腳本的提示? – 2010-01-12 07:24:29

+0

我希望用戶不能定義一個關鍵字,其中*) – zombat 2010-01-12 07:26:18

+0

我正在使用上面的鏈接功能,你已經給予,它的工作適合我... – Avinash 2010-01-12 07:30:55

回答

42
<?php 
// keywords are between * 
$str = "PHP is the *best*, its the *most popular* and *I* love it.";  
if(preg_match_all('/\*(.*?)\*/',$str,$match)) {    
     var_dump($match[1]);    
} 
?> 

輸出:

array(3) { 
    [0]=> 
    string(4) "best" 
    [1]=> 
    string(12) "most popular" 
    [2]=> 
    string(1) "I" 
} 
+3

太棒了!這麼簡單。謝謝! – 2010-01-12 07:27:19

+1

簡單而強大的答案......歡呼! – VKGS 2011-05-26 10:49:35

0

這裏亞去:

function stringBetween($string, $keyword) 
{ 
    $matches = array(); 
    $keyword = preg_quote($keyword, '~'); 

    if (preg_match_all('~' . $keyword . '(.*?)' . $keyword . '~s', $string, $matches) > 0) 
    { 
     return $matches[1]; 
    } 

    else 
    { 
     return 'No matches found!'; 
    } 
} 

使用功能是這樣的:

stringBetween('1 *a* 2 3 *a* *a* 5 *a*', '*a*'); 
3

爆炸的 「*」

​​

輸出

$ php test.php 
best 
its 
most popular 
I 
相關問題