我需要知道如何使用PHP
查找字符串中特殊字符的出现次数这是代码......
<?php
$message=$_POST['Message'];
//$rep=preg_replace("@ # $ % ^ & / . * @"," ",$message);
//$rep=preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $message);
$rep = preg_replace("/[^a-zA-Z]+/", "", $message);
echo "There are ".str_word_count($message)." words found in the given message"."<br/>";
$len=strlen($rep);
echo "length of the message is ".$len;
$delims="?#";
$word = strtok($message, $delims);
echo "delim ".$word."<br/>";
echo $delimlen=strlen($word)."<br/>";
echo "without special ".$rep;
?>
答案 0 :(得分:3)
使用此正则表达式并查看是否有帮助
$pattern = '/[!@#$%^&*()]/' // will match one occurrence of any symbol inside the []
OR
$pattern = '![^A-z0-9]!i'
int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] )
对字符串执行全局正则表达式匹配。将所有匹配的主题搜索到模式中给出的正则表达式,并按照flags指定的顺序将它们放入匹配项中。
找到第一场比赛后,后续搜索将从最后一场比赛结束时继续。
答案 1 :(得分:0)
如果您想获得更换部件的数量,您需要为preg_match调用另外2个参数,如下所示:
$replaceCount = 0;
preg_replace("/[^a-zA-Z]+/", "", $message, -1, $replaceCount);