【问题标题】:How to count the special characters in a string using PHP如何使用 PHP 计算字符串中的特殊字符
【发布时间】:2013-03-11 20:55:01
【问题描述】:

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


?>

【问题讨论】:

标签: php regex string function


【解决方案1】:

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

$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 ]]] )

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-13
      • 1970-01-01
      • 2021-05-10
      • 2017-08-01
      相关资源
      最近更新 更多