Jump to content

preg_replace


luki123

Recommended Posts

hi,

could anyone help me with a preg_replace:

 

$myString looks either like $myString1 or $myString2:

 

$myString1 = "<a href=\"http://www.outsidelink.com/\" target=\"_blank\">This </a>";

$myString2 = "<a href=\"index.php\" target=\"_self\">This </a>";

 

 

if $myString contains http://  cut out  \" and \"  (at href and target)

 

if in $myString there is NO http://  cut out  \" and \"  (at href and target) and add http://www.outsidelink.com/

 

thanks for helping

 

luki

Link to comment
https://forums.phpfreaks.com/topic/47149-preg_replace/
Share on other sites

To build on Wildbug's suggestion, essentially you're trying to remove all the " marks, that can be accomplished easily enough with:

$data = preg_replace('/"/', '', $data);

Then if its an absolute link, leave it alone. But if its just a relative link, add the base (which in this case you'll have to hardcode in). Which looks like this in regex-speak:

if(!preg_match('%https?://%', $data)) {
   $base = 'http://www.example.com/';
   $data = preg_replace('%(?<=href=)%', $base, $data);
}

Putting it all together (in my little concocted example):

$datas = array("<a href=\"http://www.outsidelink.com/\" target=\"_blank\">This1 [/url]",
   "<a href=\"index.php\" target=\"_self\">This2 [/url]",
   "<a href=\"http://www.anothersite.com/index.php\" target=\"_self\">This3 [/url]",
   "<a href=\"main.php\" target=\"_self\">This4 [/url]");

foreach($datas as $data){
        $data = preg_replace('/"/', '', $data);
        if(!preg_match('%https?://%', $data)) {
                $base = 'http://www.example.com/';
                $data = preg_replace('%(?<=href=)%', $base, $data);
        }
echo "$data \n";
}

This will give you the results you intend.

Link to comment
https://forums.phpfreaks.com/topic/47149-preg_replace/#findComment-230626
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.