Search code examples
phpregexpreg-replacepreg-replace-callback

preg_replace_callback alternative of preg_replace


I am currently using

preg_replace('/[^a-zA-Z0-9]+/', '_', $str)

what would be the alternative function using preg_replace_callback?


Solution

  • I did it myself

    function url_title($mystr){
    	$result = '';
    	$result .= preg_replace_callback(
                    '/[^a-zA-Z0-9]+/',
                    function ($matches) { return '_'; }, 
                    $mystr);
    						
    	return strtolower($result);
    }
    
    $mystr = "some string here";
    echo url_title($mystr);