Answer the question
In order to leave comments, you need to log in
What should be the regular expression to replace relative links with absolute ones (RSS)?
Good day. I really love regular expressions, but quite often I swim in them when I solve not the most trivial task. And now ... I have rss, and my task is to replace all relative paths in it with absolute ones. I came up with the following solution:
static public function relative_to_absolute( $text )
{
$rg =
'#'.
'(<\w+\s.*)'. // "<img "
'(href|src)\s*=\s*'. // "src = "
'(?:'.
'\'([^\']+)\''.'|'. // 'relative'
'\"([^\"]+)\"'. // "relative"
')'.
'#';
$replace = $text;
$index = Kohana::$base_url !== '/';
do
{
$text = $replace;
$replace = preg_replace_callback( $rg, function( $m ) use ( $index )
{
$url = empty( $m[ 3 ] ) ? $m[ 4 ] : $m[ 3 ];
if( strpos( $url, '//' ) === false )
{
return $m[ 1 ].$m[ 2 ].'="'.URL::site( $url, 'http', $index ).'"';
}
else
{
return $m[ 0 ];
}
}, $replace );
}
while( $text !== $replace );
return $replace;
}
Answer the question
In order to leave comments, you need to log in
JavaScript lacks a lot of support for regular expressions. Only the bare minimum. I know about the retrospective negative check, I myself wrote about it above :) I still haven’t figured out how to deploy it here. But I came up with a solution with a forward positive check. It turned out like this:
static public function relative_to_absolute( $text )
{
$rg =
'#'.
'(<\w+\s.*)'. // "<img "
'(href|src)\s*=\s*'. // "src = "
'(?:'.
'\'(?![\w:]+//)/?([^\']+)\''.'|'. // 'relative'
'\"(?![\w:]+//)/?([^\"]+)\"'. // "relative"
')'.
'#';
$replace = $text;
$host = self::base('http');
do
{
$text = $replace;
$replace = preg_replace( $rg, '$1$2="'.$host.'$4"', $replace );
}
while( $text !== $replace );
return $replace;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question