views:

97

answers:

1

Hello,

I have a string like this The theme song of whatever - http://www.anydomain.com/pop_new.php?sid=10623&aid=1581&rand=0.6808111508818073 #string

And now, I need to do the following thing.

  1. Get the url from above string http://www.anydomain.com/pop_new.php?sid=10623&aid=1581&rand=0.6808111508818073
  2. Replace the url to {%url%} so It should look like The theme song of whatever - {%url%} #string

Currently I am using the following code but it fails to replace the above url.

$urlregex_ = "(https?)\:\/\/[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*(\/([a-z0-9+\$_-]\.?)+)*\/?(\?[a-z+&\$_.-][a-z0-9;:@/&%=+\$_.-]*)?(#[a-z_.-][a-z0-9+\$_.-]*)?";
preg_match('~'.$urlregex_.'~',preg_replace('/\+/',' ',$url),$url_only);
$url_ = preg_replace('/ /','+',$url_only[0]);
$text = preg_replace('~'.$url_.'~','{%url%} ',$url);
return array('url' => $url_only[0], 'text' => $text);`

Hope you can help, thanks, pnm123

+2  A: 
<?php
    $orig = "The theme song of whatever - http://www.anydomain.com/pop_new.php" .
        "?sid=10623&aid=1581&rand=0.6808111508818073 #string";
    $urlregex = '~(?:https?)://[a-z0-9+$_-]+(?:\\.[a-z0-9+$_-]+)*' .
        '(?:/(?:[a-z0-9+$_-]\\.?)+)*/?(?:\\?[a-z+&$_.-][a-z0-9;:@/&%=+$_.-]*)?'.
        '(?:#[a-z_.-][a-z0-9+$_.-]*)?~i';
    if (preg_match($urlregex, $orig, $matches)) {
        $after = preg_replace($urlregex, "{%url%}", $orig);
        var_dump(array('url' => $matches[0], 'text' => $after));
    } else { //no array found
        die("oops");
    }
Artefacto
Might want to mention that `die()` is rarely a good way to handle something unexpected.
alex
@alex sure, it's just an example. I don't expect him to use `var_dump` either. This is what I did to test.
Artefacto
This just solved my problem for now... Thanks...
pnm123