php – 取得『特定字串』或『部分字串』的前方字串
在 php 5.3.0 版本以上,可以使用
1 2 3 |
strstr ( string $haystack , mixed $needle [, bool $before_needle = false ] ) |
的第三個參數值 $before_needle 為 true ,可以返回指定字串的前方字串。
但是在未滿 5.3.0 的版本呢?就必須透過另外一個技巧,例如
1 2 3 4 5 6 7 8 |
<span class="pln">$email = "user@yahoo.com.tw"; list</span><span class="pun">(</span><span class="pln">$user</span><span class="pun">,</span><span class="pln"> $therest</span><span class="pun">)</span> <span class="pun">=</span><span class="pln"> explode</span><span class="pun">(</span><span class="str">'@'</span><span class="pun">,</span><span class="pln">$email</span><span class="pun">); // $user: user // $therest: yahoo.com.tw </span> |
透過 list() 與 explode() 的組合,就可以輕易取得囉!這個 idea 真的是太棒了。
參考 http://stackoverflow.com/questions/1521898/strstr-to-show-string-before-occurance