2012-01-25 48 views
0

我有一個字符串:如何在php中查找字符串或數組中的關鍵字?

$string = "test1 - test2 - kw: test - key: 123 - test5"; 

和IM試圖得到這樣的結果:

kw = test; 
key = 123; 

我已經試過吐涎字符串:

$array = explode("-", $str); 
print_r($array); 

,其結果是:

Array 
(
    [0] => test1 
    [1] => test2 
    [2] => kw: test 
    [3] => key: 123 
    [4] => test5 
) 

在這裏,我想這樣做:

$str = 'kw:'; 
if (in_array ($str , $array)) { 
    echo 'It exists'; 
} else { 
    echo 'Does not exist'; 
} 

$kw = array_search('kw:', $array); 

$array是數組的數組。

即時通訊不知道如何從這裏開始。

有什麼想法?還有另一種提取這些詞的方法嗎?

感謝

回答

1

使用的preg_match這變得很容易:

$string = "test1 - test2 - kw: test - key: 123 - test5"; 
$results = preg_match('/.*?(kw: (.*?) -)(key: (.*?) -).*/', $string, $matches); 
var_dump($matches); 

應該返回對應匹配的數組你正在尋找...

array(5) { 
    [0]=> 
    string(43) "test1 - test2 - kw: test - key: 123 - test5" 
    [1]=> 
    string(11) "kw: test - " 
    [2]=> 
    string(4) "test" 
    [3]=> 
    string(10) "key: 123 -" 
    [4]=> 
    string(3) "123" 
} 

欲瞭解更多信息關於正則表達式(非常強大的工具):

http://www.regular-expressions.info/tutorial.html

+0

我得到'int(1)'。 – Patrioticcow

+0

關閉:如果你想找到多於一個匹配,並且你需要通過$匹配作爲第三個參數,你需要'preg_match_all()' –

+0

@Patrioticcow我測試並更新了錯誤的代碼以及錯誤... –

1

這裏有一個循環,看起來在

的子 kw:key:
$string = "test1 - test2 - kw: test - key: 123 - test5"; 
$array = explode("-", $string); 

foreach ($array as $part) { 
    if (substr(trim($part), 0, 3) == 'kw:') { 
    list($kw, $kwval) = explode(' ' , trim($part)); 
    echo "kw: $kwval\n"; 
    } 
    if (substr(trim($part), 0, 4) == 'key:') { 
    list($key, $keyval) = explode(' ' , trim($part)); 
    echo "key: $keyval\n"; 
    } 
} 


// Output: 
// kw: test 
// key: 123 
+0

嗯,我看不到結果。現在請參閱http://ideone.com/6RIqs – Patrioticcow

+0

。謝謝 – Patrioticcow

+0

@Patrioticcow,因爲你在第一個'explode()'調用中有錯誤的變量。使用'$ string'而不是'$ str'。我在其中一個編輯中找到並修復了這個問題。 –

1
php > $string="test1 - test2 - kw: test - key: 123 - test5"; 
php > $pattern="/\ \-\ (\w+)\:\s([^\s]+)/"; 
php > echo preg_match_all($pattern,$string,$matches); 
2 
php > print_r($matches); 
Array 
(
    [0] => Array 
     (
      [0] => - kw: test 
      [1] => - key: 123 
     ) 

    [1] => Array 
     (
      [0] => kw 
      [1] => key 
     ) 

    [2] => Array 
     (
      [0] => test 
      [1] => 123 
     ) 

) 
php > 
1

不優雅,但:

$string = "test1 - test2 - kw: test - key: 123 - test5"; 

$array = explode(" - ", $string); 

foreach ($array as $v) { 
    if (strstr($v,"kw: ")) { 
     $kw = substr($v,4); 
    } 
    if (strstr($v,"key: ")) { 
     $key = substr($v,5); 
    } 
} 

echo "kw = " . $kw; 
echo "key = " . $key;