0

我需要知道如何使用 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;


?>
4

2 回答 2

3

使用这个正则表达式,看看这是否有帮助

$pattern = '/[!@#$%^&*()]/'  // will match one occurrence of any symbol inside the []

或者

$pattern =  '![^A-z0-9]!i'

preg_match_all

int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] )

对字符串执行全局正则表达式匹配。搜索主题以查找与模式中给出的正则表达式的所有匹配项,并按照标志指定的顺序将它们放入匹配项中。

找到第一个匹配后,从最后一个匹配的末尾继续进行后续搜索。

于 2013-03-11T12:49:41.987 回答
0

如果您想获得更换零件的数量,您的 preg_match 调用需要另外 2 个参数,如下所示:

$replaceCount = 0;
preg_replace("/[^a-zA-Z]+/", "", $message, -1, $replaceCount);
于 2013-03-11T12:55:01.573 回答