如何使用PHP计算字符串中的特殊字符

时间:2021-04-25 20:17:59

I need to know how to find the number of occurrences of special characters in a string using PHP

我需要知道如何使用PHP查找字符串中特殊字符的出现次数

Here is the code...

这是代码......

<?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;


?>

2 个解决方案

#1


3  

use this regex and see whether this helps

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

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

OR

要么

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

preg_match_all

preg_match_all

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

Perform a global regular expression match against a string. Searches subject for all matches to the regular expression given in pattern and puts them in matches in the order specified by flags.

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

After the first match is found, the subsequent searches are continued on from end of the last match.

找到第一个匹配后,后续搜索将从最后一个匹配结束时继续。

#2


0  

If you want to get the number of replaced parts you need 2 more parameters for your preg_match call like this:

如果你想获得更换部件的数量,你需要为preg_match调用增加2个参数,如下所示:

$replaceCount = 0;
preg_replace("/[^a-zA-Z]+/", "", $message, -1, $replaceCount);

#1


3  

use this regex and see whether this helps

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

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

OR

要么

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

preg_match_all

preg_match_all

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

Perform a global regular expression match against a string. Searches subject for all matches to the regular expression given in pattern and puts them in matches in the order specified by flags.

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

After the first match is found, the subsequent searches are continued on from end of the last match.

找到第一个匹配后,后续搜索将从最后一个匹配结束时继续。

#2


0  

If you want to get the number of replaced parts you need 2 more parameters for your preg_match call like this:

如果你想获得更换部件的数量,你需要为preg_match调用增加2个参数,如下所示:

$replaceCount = 0;
preg_replace("/[^a-zA-Z]+/", "", $message, -1, $replaceCount);