【发布时间】:2013-03-25 10:15:19
【问题描述】:
如何使用 PHP 删除字符串开头(首字母应为字母数字)中的所有特殊字符?请
$String = "+&,Hello+{+ +$world";
删除字符串开头的所有特殊字符后
字符串应该变成“Hello+{+ +$world”
帮帮我。
【问题讨论】:
-
请告诉我匹配的 URL 吗?
如何使用 PHP 删除字符串开头(首字母应为字母数字)中的所有特殊字符?请
$String = "+&,Hello+{+ +$world";
删除字符串开头的所有特殊字符后
字符串应该变成“Hello+{+ +$world”
帮帮我。
【问题讨论】:
这将替换开头的所有非字母数字:
preg_replace('/^([^a-zA-Z0-9])*/', '', $string);
更新:
如果您需要修剪字符串开头和结尾的非字母数字字符,请使用:
<?php
$string = "++&5Hello ++f s world6f++&ht6__) ";
echo preg_replace('/(^([^a-zA-Z0-9])*|([^a-zA-Z0-9])*$)/', '', $string);
【讨论】:
尝试使用trim 了解更多信息,请参阅http://php.net/manual/en/function.trim.php
要从字符串开头删除,您可以使用ltrim http://www.php.net/manual/en/function.ltrim.php
要从字符串末尾删除,您可以使用rtrim
http://www.php.net/manual/en/function.rtrim.php
您的示例代码
$String = "+&,Hello+{+ +$world";
echo ltrim($String,"&+,");
您可以在 ltrim 中添加更多字符以从字符串的第一个中删除
【讨论】:
<?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);
?>
【讨论】:
试试这个
preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $String);
【讨论】:
使用 trim - 这是一个内置功能: http://php.net/manual/en/function.trim.php
【讨论】:
我认为使用 ltrim 会更有用,因为您想在字符串的开头删除:http://www.php.net/manual/en/function.ltrim.php
【讨论】: