PHP从字符串中获取url等等

时间:2010-06-07 01:31:30

标签: php string url preg-replace preg-match

我有一个像The theme song of whatever - http://www.anydomain.com/pop_new.php?sid=10623&aid=1581&rand=0.6808111508818073 #string

这样的字符串

现在,我需要做以下事情。

  1. 从字符串http://www.anydomain.com/pop_new.php?sid=10623&aid=1581&rand=0.6808111508818073
  2. 上方获取网址
  3. 将网址替换为{%url%},以使它看起来像The theme song of whatever - {%url%} #string
  4. 目前我使用的是以下代码,但无法替换上述网址。

    $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);`
    

    希望你能帮忙,谢谢,pnm123

1 个答案:

答案 0 :(得分:2)

<?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");
    }