luki123 Posted April 15, 2007 Share Posted April 15, 2007 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 Quote Link to comment Share on other sites More sharing options...
ted_chou12 Posted April 15, 2007 Share Posted April 15, 2007 can you use the code tags, these codes dont look very neat with out them. Ted Quote Link to comment Share on other sites More sharing options...
pro_se Posted April 16, 2007 Share Posted April 16, 2007 So, what are you trying to do? Quote Link to comment Share on other sites More sharing options...
Wildbug Posted April 16, 2007 Share Posted April 16, 2007 Use an if condition. if (strpos('http://',$myString) !== false) { //... preg_replace, etc } else { //... preg_replace, etc } Quote Link to comment Share on other sites More sharing options...
c4onastick Posted April 16, 2007 Share Posted April 16, 2007 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.