[英]Removing special characters and space from string
我必須將帖子存儲到數據庫。 我想將帖子標題存儲為帖子URL,因此我需要刪除特殊字符和空格。 我已經做到了。 一切工作正常,但是當我在字符串的最后給出空格時,最后顯示連字符,如下所示。
前abcd_
如果有空格,我只想刪除最后一個連字符。
到目前為止,我已經嘗試過-
function clean($post_name) {
$post_name = str_replace(' ', '-', $post_name);
return preg_replace('/[^A-Za-z0-9\-]/', '', $post_name);
}
$post_url=clean($post_name);
這怎么可能?
謝謝。
嘗試在str_replace()
之前trim()
str_replace()
$post_name = str_replace(' ', '-', trim($post_name));
要解決您的問題,這是我的1%
function clean($post_name) {
$post_name = trim($post_name);
嘗試這樣。trim trim()
函數從字符串的兩側刪除空格和其他預定義字符。
function clean($post_name) {
$name = trim($post_name);
$post_name = str_replace(' ', '-', $name);
return preg_replace('/[^A-Za-z0-9\-]/', '', $post_name);
}
$post_url=clean($post_name);
只需檢查給定字符串的最后兩個字符。 然后根據定義分配子字符串。 您將可以在if塊中添加更多“定義的字符”進行檢查。
$len = strlen($post_name)
// check if last two characters are ' -'
if ( substr($post_name, $len -2, $len) === ' -' ) {
// assign all but the last two characters.
$post_name = substr($post_name, 0, $len -2);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.