[英]php string replace remove & add word at the end
也許真的很簡單,但是我無法理解如何使用str_replace
對多個短語執行以下操作:
注意:這始終是我要保留的最后一個字(即倫敦,伯明翰和蘇格蘭或其他任何地方)。
短語示例
我愛倫敦
住在伯明翰附近
蘇格蘭演奏
要變成:
今天在倫敦
今天在伯明翰
今天在蘇格蘭
謝謝
您可能無法在沒有更多代碼的情況下使用str_replace()
:
preg_match('/\w+$/', $string, $match);
echo $match[0];
或例如替換:
$result = preg_replace('/.*?(\w+)$/', 'In $1 Today', $string);
使用正則表達式和preg_replace()
一步即可做到:
print preg_replace('/.* (\w+)\W*/', 'In \1 today', "I love London");
通過忽略最后一個單詞之后的標點或空格,我使它比您預期的更健壯。
或者,將相同的正則表達式與整個字符串列表一起使用:
$data = array("I love London",
"I live in Birmingham!",
"Living near Birmingham!",
"Playing by Scotland..."
);
$results = preg_replace('/.* (\w+)\W*/', 'In \1 today', $data);
foreach ($results as $string)
print $string, "\n";
echo str_replace(array("I Love London","Living near Birmingham","Playing by Scotland"), array("In London Today","In Birmingham Today","In Scotland Today"), "I Love London Living near Birmingham Playing by Scotland");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.