danielstjules / Stringy

A PHP string manipulation library with multibyte support
MIT License
2.46k stars 216 forks source link

preg_replace(): Compilation failed: invalid range in character class at offset 12 #191

Open dbetts opened 5 years ago

dbetts commented 5 years ago

On line 813 of Stringify.php there is a function called slugify(). I had to add an escape character in the regex pattern on the dash or hyphen to prevent the error message. I'm not sure if that hyphen was intended to be unescaped. I made the following change to that function to prevent the error and allow the pages to load correctly.

Apparently the hyphen needs to be either the first or last character in the pattern, or escaped: invalid range in character class

public function slugify($replacement = '-') { $stringy = $this->toAscii();

    $quotedReplacement = preg_quote($replacement);

// $pattern = "/[^a-zA-Z\d\s-$quotedReplacement]/u"; // Commented this out. $pattern = "/[^a-zA-Z\d\s-$quotedReplacement]/u"; // Added backslash in front of the hyphen. $stringy->str = preg_replace($pattern, '', $stringy);

    return $stringy->toLowerCase()->delimit($replacement)
                   ->removeLeft($replacement)->removeRight($replacement);
}
jonaseberle commented 5 years ago

With PHP 7.3 it is necessary to escape - when used in character classes but not as range. So this is the corrected line: $pattern = "/[^a-zA-Z\\d\\s\\-_$quotedReplacement]/u";

odahcam commented 1 year ago

Same error happening in PHP 8.0:

image

The error actually happen because the preg_replace in line 1174 actually replaces all characters in the stringy with '' because of the wrong regex pattern you mentioned.

This is preventing our application to go to production, is there anyway we can help you fix this or make a release with the fix get published faster?

odahcam commented 1 year ago

Well, I'm simply going with https://github.com/statamic/Stringy for now.