1

How to count all the special characters on a string ? example:

$sample_string = "!!~~Sample string";
echo substr($sample_string, special character);

so the output will be 4.

1
  • Is it possible that the special chars are distributend randomly in the string? Not all sequentially at then beginning? Commented Oct 12, 2015 at 7:30

3 Answers 3

3

By Regex

$sample_string = "!!~~Sample string";

preg_match_all("/\W/",$sample_string,$match);

echo count($match);
Sign up to request clarification or add additional context in comments.

Comments

1

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

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.

Comments

0

You can simply use preg_replace_callback function along with closure like as

$sample_string = "!!~~Sample string";
$count = 0;
preg_replace_callback('/[^\h\w]/', function($m)use(&$count) {
    $count++;
}, $sample_string);
echo $count;//4

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.