问题
I use the following to find all URL´s inside $content
$content = preg_match_all( '/(http[s]?:[^\s]*)/i', $content, $links );
But this will depend on the http://
part in http://www.google.com/some/path
.
My questions are :
1 - How can I modify it in order to hit also the links that are start with only www
, e.g. www.google.com
?
2 - The main aim is to find the links, and replace them with a value that is returned from another function. I tried preg_match_callback() , but it is not working (probably using it wrong ..
$content = preg_replace_callback(
"/(http[s]?:[^\s]*)/i",
"my_callback",
$content);
function my_callback(){
// do a lot of stuff independently of preg_replace
// adding to =.output...
return $output;
}
Now , in my logic (which is probably wrong ) all matches from the $content
would be replaced by $output
. what am I doing wrong ?
(please no anonymous functions - i am testing on an old server)
EDIT I - after comments , trying to clarify with more details
function o99_simple_parse($content){
$content = preg_replace_callback( '/(http[s]?:[^\s]*)/i', 'o99_simple_callback', $content );
return $content;
}
callback :
function o99_simple_callback($url){
// how to get the URL which is actually the match? and width ??
$url = esc_url_raw( $link );
$url_name = parse_url($url);
$url_name = $description = $url_name['host'];// get rid of http://..
$url = 'http://something' . urlencode($url) . '?w=' . $width ;
return $url; // what i really need to replace
}
回答1:
To modify the regex you already have to allow URLs that begin with www
, you'd simply write this:
/((http[s]?:|www[.])[^\s]*)/i
+ ++++++++
来源:https://stackoverflow.com/questions/15650994/php-matching-urls-and-using-preg-replace-callback