2013-03-25 104 views
0

如何刪除所有特殊字符在開始(首字母應該是字母數字)使用PHP的字符串?請刪除所有特殊字符在使用PHP的字符串開始

$ String =「+ &,Hello + {+ + $ world」;

刪除後的字符串

該字符串應該成爲「你好+ {+ + $世界」

幫我開始所有特殊字符。

+0

告訴我匹配的URL PLease? – soavahaf 2013-03-25 10:24:39

回答

1

這將替換在開始的時候一切是不是字母:

preg_replace('/^([^a-zA-Z0-9])*/', '', $string); 

UPDATE:

如果同時需要在開始和字符串的結尾處使用該修剪非字母數字字符:

<?php 

$string = "++&5Hello ++f s world6f++&ht6__) "; 

echo preg_replace('/(^([^a-zA-Z0-9])*|([^a-zA-Z0-9])*$)/', '', $string); 
+0

錯誤顯示如下警告:preg_replace()[function.preg-replace]:編譯失敗:在第5行的C:\ xampp \ htdocs \ test.php中的偏移量16處沒有重複內容 – soavahaf 2013-03-25 10:37:21

+0

@soavahaf現在修復:) – 2013-03-25 11:05:44

+0

Tell我也如何使用PHP刪除每個字符串的開始和結束的所有特殊字符?請 。 – soavahaf 2013-03-25 11:41:50

0

試試這個

preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $String); 
+0

否這不起作用。 – soavahaf 2013-03-25 10:19:03

+0

正確地詢問您的問題 – 2013-03-25 10:32:59

0

我想使用LTRIM將會更有用,因爲您希望在字符串開頭刪除:http://www.php.net/manual/en/function.ltrim.php

+0

請給我一個代碼示例 – soavahaf 2013-03-25 10:31:36

+0

您能分享一下您正在尋找的示例嗎? – Devesh 2013-03-25 10:37:05

+0

$ String =「+&,Hello + {+ + $ world」;從字符串開頭刪除特殊字符後,字符串將打印爲「Hello + {+ + $ world」 – soavahaf 2013-03-25 10:41:25

1
<?php 
function string_cleaner($result) 
{ 
    $result = strip_tags($result); 
    $result = preg_replace('/[^\da-z]/i', ' ', $result); 
    $result = preg_replace('/&.+?;/', '', $result); 
    $result = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', ' ', $result); 
    $result = preg_replace('|-+|', ' ', $result); 
    $result = preg_replace('/_+/', ' ', $result); 
    $result = preg_replace('/&#?[a-z0-9]+;/i','',$result); 
    $result = preg_replace('/[^%A-Za-z0-9 _-]/', ' ', $result); 
    $result = preg_replace('/^\W+|\W+$/', '', $result); 
    $result = preg_replace('/\s+/', ' ', $result); 
    $result = trim($result, ' '); 
    return $result; 
} 
?> 

<?php 
echo string_cleaner($content); 
?> 
+0

否這是行不通的 – soavahaf 2013-03-25 10:31:16

+0

試試這個$ result = preg_replace('/^\ W + | \ W + $ /','',$ result); – Devan 2013-03-25 10:54:25

+0

這段代碼究竟在做什麼?爲什麼你需要這麼多不同的正則表達式? – Jocelyn 2013-03-25 12:02:19

相關問題