0

I need to know how to find the number of occurrences of special characters in a string using 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;


?>
w5m
  • 2,286
  • 3
  • 34
  • 46

2 Answers2

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

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.

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

Techie
  • 44,706
  • 42
  • 157
  • 243
0

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

$replaceCount = 0;
preg_replace("/[^a-zA-Z]+/", "", $message, -1, $replaceCount);
Andras Toth
  • 576
  • 4
  • 11