替代方法
取得第一次出現之前的全部文字。
-----------------------------------------------
包含搜尋目標
$string1 = "我需要餅乾和汽水。";
$needle = "餅乾";
// 找出搜尋目標的長度
$needle_len = strlen($needle);
// 找出位置
$position_num = strpos($string1, $needle) + $needle_len;
// 切割字串
$result_string = substr($string1, 0, $position_num);
// 顯示結果
echo $result_string; // I need cookies
-----------------------------------------------
簡潔版本
$result_string = substr($string1, 0, strpos($string1, $needle) + strlen($needle));
echo $result_string; // I need cookies
-----------------------------------------------
不包含needle
$result_string = substr($string1, 0, strpos($string1, $needle));
echo $result_string; // I need
-----------------------------------------------
免費電子郵件垃圾?
這可能對處理電子郵件很有用。
例如,有人從 Yahoo 帳戶發送電子郵件到您的伺服器。
免費電子郵件總是帶有一些無用的東西,例如...
"Do you Yahoo!? The New Yahoo! Shopping - with improved product search"。
我們可以這樣刪除這個片語
$needle = "Do you Yahoo!?";
$result_string = substr($emailstring, 0, strpos($emailstring, $needle));