Question

I want to delete all the short word set, which start and end with == ==, like == some text ==. I want to make that work with preg_replace, but it did not work. This is my code:

$string = preg_replace('/[==][ ][a-z|A-Z|0-9][ ][==]/', "", $string);
Was it helpful?

Solution

One possible approach:

$string = preg_replace('/==.*?==/', '', $string);

Yes, I know that the original pattern has additional checks, but I really doubt those will be useful. For completeness sake, though, here's the (most probably) original intent, written in proper regexian:

$string = preg_replace('/== [a-zA-Z0-9]+ ==/', '', $string);

In your current regex you severely misuse the character classes (defined with brackets). First, character classes are useful for alternating between single characters only, so [==] is actually the same as [=] (and is less efficient in raw than just =).

Second, using alternation within the class itself is just meaningless: [a-z|A-Z|0-9] actually matches both letters, digits AND | sign. Proper way of using this class is [a-zA-Z0-9].

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top