Home > Blockchain >  Keep getting this message: preg_replace(): Compilation failed: quantifier does not follow a repeatab
Keep getting this message: preg_replace(): Compilation failed: quantifier does not follow a repeatab

Time:10-28

Keep getting this message:

PHP Warning:  preg_replace(): Compilation failed: quantifier does not follow a repeatable item at offset 2 in ...

Here's the applicable excerpt from the config file:

// config file excerpt:
'swap_image_refs' => [
    'callback' => new \SimpleHtml\Transform\ReplaceRegex(),
    'params' => ['regex' => '!/( *?)/images/!', 'replace' => '/images/$1/'],
],

Here's the __invoke() method from the class called:

public function __invoke(string $html, array $params = []) : string
{
    $regex = $params['regex'] ?? '';
    $replace = $params['replace'] ?? '';
    $text = (!empty($regex))
          ? preg_replace($regex, $replace, $html)
          : $html;
    return $text ?? $html;
}

The code works ... but the replacement wasn't made.

CodePudding user response:

Pulling out the pertinent bits, you get this:

$regex = '!/( *?)/images/!';
$replace = '/images/$1/';
$contents = file_get_contents('https://unlikelysource.com/about');
$text = preg_replace($regex, $replace, $contents);

The problem is in the regex (is always is, isn't it?). The regex, as stated doesn't match anything! Here's the corrected regex:

$regex = '!/(. ?)/images/!';

Hope this helps somebody.

CodePudding user response:

The separation of qualifiers and quantifiers is a basic concept of regular expressions. You define what to match and how often.

*? are all quantifiers, they specify how often something should match. So you're missing what to match.

Try (/(. )/images/)

  • The . is an qualifier that represents any character (except \n, depending on modifier s).

  • means at least once

  • () can be used as delimiters without loosing the special meaning - just treat it as group 0

  • * is the quantifier meaning "any amount" - it doesn't do anything in this case.

  • ? can have two meanings. If it follows a or * it will trigger ungreedy (shortest) matches. Following a qualifier it means none or one.

  • Related