PHP Regex help (conversion from preg_match_all to preg_replace)

I'm having difficulty converting some regular expression from use to preg_match_all for use in preg_replace.

Basically, only through regular expression, I would like to combine uppercase characters that are preceded by either a space, the beginning of the text, or hypen. This is not a problem, for this I have the following:

preg_match_all('/(?<= |\A|-)[A-Z]/',$str,$results);
echo '<pre>' . print_r($results,true) . '</pre>';

Now, what I would like to do is use preg_replace to return only a string with uppercase letters that match my criteria above. If I output the regex directly to preg_replace, then it obviously replaces the characters that I want to keep.

Any help would be greatly appreciated :)

In addition, I fully understand that regex is not the best solution for this in terms of efficiency, but I would like to use preg_replace nonetheless.

+3
source share
2 answers

According to the laws of De Morgan ,
if you want to keep the letters

  • A-Z and
  • preceded by [space], \Aor-

then you want to delete characters that

  • not A-Z, or
  • not preceded by [space], \Aor-

Perhaps this is (replace the match with an empty string)?

/[^A-Z]|(?<! |\A|-)./

See an example here .

+2
source

I think it will be something like this:

$sString = preg_replace('@.*?(?<= |\A|-)([A-Z])([a-z]+)@m',"$1", $sString);
+1
source

All Articles