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 Link to comment https://forums.phpfreaks.com/topic/47149-preg_replace/ 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 Link to comment https://forums.phpfreaks.com/topic/47149-preg_replace/#findComment-229932 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? Link to comment https://forums.phpfreaks.com/topic/47149-preg_replace/#findComment-229989 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 } Link to comment https://forums.phpfreaks.com/topic/47149-preg_replace/#findComment-230529 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. Link to comment https://forums.phpfreaks.com/topic/47149-preg_replace/#findComment-230626 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.