Search code examples
phpregexpreg-replace-callback

Can preg_replace_callback() preserve elements of the variable?


I've got a series of large markdown strings that contain URLs, most of the URLs are fine, but a number of them were broken when changing the formatting, they had a number of dashes ("-") changed into whitespace characters.

I've been trying to use preg_replace_callback() to fix these when they are loaded in PHP.

Examples:

[Site Name](http://www.siteurl.com/this-is-the-website broken url)

Since these are all contained with in large strings (that usually have 4-5 paragraphs of text) and may have 1-3+ URLs in the text, I need to iterate over them, capture the string, remove the whitespace replacing it with a dash and return it to the right location.

Currently I've got the matching taken care of:

$postBody = preg_replace_callback("^(\([A-Za-z\:\/0-9\-.\s]*\))^",'urlcallback', $postBody);

And I've tried to create the function:

function urlcallback ($matches) {
static $id = 0;
$matches[$id] = preg_replace("^\s^", "-", $matches);
return $matches[$id];
$id++;
}

My understanding of preg_replace_callback() was that it would call the function each time it encounters a match in the string, and place the return of the function at that spot, but as I am getting the error:

Notice: Array to string conversion in cleanup.php at line 139

And line 139 is my early $postBody declaration, I assume that preg_replace_callback() is dealing with all the matches at the same time, so I'm not sure how to pass them back into the string while only changing the whitespaces in each one?


Solution

  • Problem seems to be this line:

    $matches[$id] = preg_replace("^\s", "-", $matches);
    

    As $matches is an array not a string value.

    It should be:

    $matches[$id] = preg_replace('/\s/', "-", $matches[0]);
    

    $matches[0] represents whole matched string from preg_replace_callback function call.