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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.