Click to See Complete Forum and Search --> : preg_replace - patten problem


Scleppel
03-18-2005, 03:12 PM
Ok, this is a small example of what happens in my script.
Sorry if the code errors because of unescaped quotes.

<?php

$p_domain = 'localhost'; //These variables are made by the script
$real_url_dir = 'domain.net'; //this variable sometimes has a directory aswell

$html = 'href="http://localhost/?domain.net/dir/style.css"' . "\n" .
'href=\\'http://localhost/?domain.net/dir/style.css\\'' . "\n" .
'href=http://localhost/?domain.net/dir/style.css' . "\n" .
'href="dir/style.css"' . "\n" .
'href=\\'dir/style.css\\'' . "\n" .
'href=dir/style.css' . "\n";

$search = array("'href=\\"[^(http://{$p_domain}/?http://)]'si",
"'href=\\'[^(http://{$p_domain}/?http://)]'si",
"'href=[^(\"|\\'|)(http://{$p_domain}/?http://)]'si");

$replace = array("href=\\"http://{$p_domain}/?{$real_url_dir}/",
"href='http://{$p_domain}/?{$real_url_dir}/",
"href=http://{$p_domain}/?{$real_url_dir}/");

$clean_html = preg_replace($search, $replace, $html);

echo $clean_html;

?>
The output is
href="http://localhost/?domain.net/dir/style.css"
href='http://localhost/?domain.net/dir/style.css'
href=http://localhost/?domain.net/dir/style.css
href="http://localhost/?domain.net/ir/style.css"
href='http://localhost/?domain.net/ir/style.css'
href=http://localhost/?domain.net/ir/style.css

The problem is that the second block of urls have the d of dir missing. Does anyone know how to stop them from disapearing?

ShrineDesigns
03-19-2005, 02:48 PM
try this regExp patternhttp:\/\/([^\/]+)\/([^\/]+)\/

Scleppel
03-19-2005, 03:11 PM
unfortunately i couldn't get it to work, i wasn't sure where exactly to put it in my code. The point of the code is to change the relative urls to be like the ones before them. I just need it to search for any links that arn't 'href="http://' and change them.

Oops, i forgot to say thank you :(, so thank you.

ShrineDesigns
03-19-2005, 04:04 PM
ok, try['"](\.*\/)([^'"]+)['"]the pattern within the () should match any relative or absolute uri, example<?php
$uri = '../path/to/file';

echo preg_replace("/(\\.*\\/)+(.+)/", "http://www.example.com/\\2", $uri); // output: http://www.exampe.com/path/to/file
?>