Search code examples
phppreg-replace-callback

Preg Callback Issue


Great Mates... I need your help.. please let me know why this code is not getting in to the callback function...

  wppp_content_hook('<p><a href="http://localhost/work/Kate/wp-content/uploads/2011/05/amg_sls_01.jpg"><img width="300" height="250" class="alignleft size-medium wp-image-195" title="amg_sls_0" alt="" src="http://localhost/work/Kate/wp-content/uploads/2011/05/amg_sls_01-300x250.jpg"></a></p>');

  function wppp_content_hook($content) {

    $fileTypes        = array('\.bmp|\.gif|\.jpg|\.jpeg|\.png');
    $pattern          = array();
    $rel              = 'wp-prettyPhoto';
    $pattern[]        = "/<a(.*?)href=('|\")([A-Za-z0-9\/_\.\~\:-]*?)($fileTypes)('|\")(.*?)>/i";
    $pattern[]        = "/<a(.*?)href=('|\")([A-Za-z0-9\/_\.\~\:-]*?)($fileTypes)('|\")(.*?)(rel=('|\")".$rel."(.*?)('|\"))([ \t\r\n\v\f]*?)((rel=('|\")".$rel."(.*?)('|\"))?)([ \t\r\n\v\f]?)([^\>]*?)>/i";


    return  preg_replace_callback($pattern,'_regexCallback',$content);
  }

  function _regexCallback($matches) {
   echo "<pre>";
    print_r($matches);
   echo "</pre>";  
    global $post;
    $fileTypes        = array('\.bmp|\.gif|\.jpg|\.jpeg|\.png');
    $rel            = 'wp-prettyPhoto';
    $pattern        = array();
    $replacement    = array();
    $pattern[]      = "/<a(.*?)href=('|\")([A-Za-z0-9\/_\.\~\:-]*?)($fileTypes)('|\")(.*?)>/i";
    $pattern[]      = "/<a(.*?)href=('|\")([A-Za-z0-9\/_\.\~\:-]*?)($fileTypes)('|\")(.*?)(rel=('|\")".$rel."(.*?)('|\"))([ \t\r\n\v\f]*?)((rel=('|\")".$rel."(.*?)('|\"))?)([ \t\r\n\v\f]?)([^\>]*?)>/i";
    $replacement[]  = '<a$1href=$2$3$4$5$6 rel="'.$rel.'[g'.$post->ID.']">';
    $replacement[]  = '<a$1href=$2$3$4$5$6$7>';

    return !strpos($matches['0'], '_blank')? preg_replace($pattern,$replacement,$matches['0']) : $matches['0'];
  }

Solution

  • Because your $pattern does not match $content

    Look precisely at your actual regexps by var_export'ing $pattern

    Callback will only be executed if your content will be matched by regular expression. No reason to execute callback function otherwise since there are no matches.

    Part of your actual regex: ([A-Za-z0-9\\/_\\.\\~\\:-]*?)(Array)

    It seems like not desired "Array" sneaked into your pattern (both of them).