2010-06-07 45 views
2

我有這樣The theme song of whatever - http://www.anydomain.com/pop_new.php?sid=10623&aid=1581&rand=0.6808111508818073 #stringPHP獲取URL一個字符串和一些更

字符串而現在,我需要做下面的事情。

  1. 從上面的字符串http://www.anydomain.com/pop_new.php?sid=10623&aid=1581&rand=0.6808111508818073
  2. 獲取替換URL網址{%URL%}所以它應該看起來像The theme song of whatever - {%url%} #string

目前我使用下面的代碼,但它無法取代上面的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);` 

希望能幫到你,謝謝你,pnm123

回答

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

可能要提及的是'死()'是很少去處理一些意想不到的好方法。 – alex 2010-06-07 01:56:43

+0

@alex當然,這只是一個例子。我不指望他也使用'var_dump'。這是我做的測試。 – Artefacto 2010-06-07 02:02:48

+0

這剛剛解決了我的問題,現在...謝謝... – pnm123 2010-06-07 02:06:03