• I am writing a function to filter post content that will perform a regex substitution using preg_replace. My end goal is to find any YouTube URLs in a post and add parameters to them. If the parameters are already there, then they should not be added again.

    When I test the regex, it works the way I want. This test demonstrates that the replacement is made when needed…

    https://regex101.com/r/kS1wU3/1

    … while this test shows that the replacement is NOT made when it ISN’T needed; that is, when the added parameters are already there.

    https://regex101.com/r/kS1wU3/2

    However, when I use this regex in my function, the replacement isn’t made. If I remove the newline from the end of the regex, then the parameters are added even if they are already present, and the URL gets longer with each save.

    Can anyone help with this? Or is there an entirely different way to alter YouTube parameters that doesn’t involve preg_replace at all?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter mbrailer

    (@mbrailer)

    Here is my function. The regex evaluates correctly in the tester but it doesn’t work within this function.

    function youtube_add_params($content){
    	$mod_content = preg_replace('/(?:https?:\/\/)?(?:youtu\.be\/|(?:www\.)?youtube\.com\/watch(?:\.php)?\?.*v=)([a-zA-Z0-9\-_]+)\n/m', 'https://www.youtube\.com\/watch\?v=${1}&rel=0&showinfo=0', $content);
    	return $mod_content;
    }
    add_filter('content_save_pre', 'youtube_add_params');
    Moderator bcworkz

    (@bcworkz)

    You don’t want to match a newline because the URLs could end in any number of whitespace chars, so match whitespace with \s. In fact, capture it and include it in your replacement so whatever whitespace was used is maintained. I doubt you really need the m flag either.

    I think that was all the problem was.
    $mod_content = preg_replace('/(?:https?:\/\/)?(?:youtu\.be\/|(?:www\.)?youtube\.com\/watch(?:\.php)?\?.*v=)([a-zA-Z0-9\-_]+)(\s)/', 'https://www.youtube\.com\/watch\?v=${1}&rel=0&showinfo=0${2}', $content);

    Untested in WP, works fine in the tester, but then so did your version ??

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Question about preg_replace’ is closed to new replies.