2015-10-26 20 views
1

如果我有文字如一串:找到PHP字符串,並保存爲變量

<p>Hello world here is the latest news ##news?123## or click here to read more</p> 

我想通過字符串來看看,發現什麼開始##news?然後我想保存和ID 123和尾隨哈希作爲變量,所以最後的結果將是:

$myvar == "##news?123##" 

我如何使用PHP來讀取輸入字符串並保存特定部分作爲一個變量?

回答

1

假設你不是試圖解析HTML,但正如你所說,只要找到任何以「## news?」開頭的事件。那麼你可以在這裏愉快地使用正則表達式:

$string = '<p>Hello world here is the latest news ##news?123## or click here to read more'; 
$matches = array(); 
preg_match_all("/(##news\?.*?)\s/",$string,$matches); 
print_r($matches); 
+0

完美謝謝:-) – Jack

2

preg_match是你的朋友對這類問題。

 $str='<p>Hello world here is the latest news ##news?123## or click here to read more'; 
     $pttn='@(##news\?(\d+)##)@'; 
     preg_match($pttn, $str, $matches); 

     $myvar=$matches[0]; 
     $id=$matches[2]; 

     echo $myvar.' '.$id; 
+0

我覺得你的模式是它比我:)可能會更好 –

+1

沒有多少真正的 – RamRaider