Skip to content

Instantly share code, notes, and snippets.

@zavakid
Created July 4, 2012 05:43
Show Gist options
  • Save zavakid/3045599 to your computer and use it in GitHub Desktop.
Save zavakid/3045599 to your computer and use it in GitHub Desktop.
replace with regex and callback in PHP
<?php
function urlReplace($text, $replaceWith){
// set the callback function
$callback = function($match)use($replaceWith){
$replaced0 =preg_replace('/\{0\}/', $match[0], $replaceWith);
return preg_replace('/\{1\}/', toUpper($match[0]), $replaced0);
};
var_dump($callback);
return preg_replace_callback('/https?:\/\/\S+(?= |$)/',$callback, $text);
}
function toUpper($input){
return strtoupper($input);
}
// test
$s = "http://www.bitbucket.com here and https://github.com there";
$result = urlReplace($s, '<a href={0}>{1}</a>');
echo $result;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment