本文介紹了刪除字符串的一部分,但僅當它位于字符串末尾時的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我需要刪除字符串的子字符串,但前提是它位于字符串的末尾.
I need to remove a substring of a string, but only when it is at the END of the string.
例如,刪除以下字符串末尾的 'string' :
for example, removing 'string' at the end of the following strings :
"this is a test string" -> "this is a test "
"this string is a test string" - > "this string is a test "
"this string is a test" -> "this string is a test"
有什么想法嗎?可能是某種 preg_replace,但如何??
Any idea's ? Probably some kind of preg_replace, but how??
推薦答案
您會注意到 $
字符的使用,它表示字符串的結尾:
You'll note the use of the $
character, which denotes the end of a string:
$new_str = preg_replace('/string$/', '', $str);
如果字符串是用戶提供的變量,最好先通過 preg_quote
運行它:
If the string is a user supplied variable, it is a good idea to run it through preg_quote
first:
$remove = $_GET['remove']; // or whatever the case may be
$new_str = preg_replace('/'. preg_quote($remove, '/') . '$/', '', $str);
這篇關于刪除字符串的一部分,但僅當它位于字符串末尾時的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!