Php - 将url解析为友好(使用regexp)

问题描述:

Using regex I need convert this string url.

<a class="navPages" href="?mode=author&amp;id=9&amp;word=friend&fn=%d">%s</a>

To get a output format like this:

<a class="navPages" href="author/9/friend/page/%d>%s</a>

Or get result:

0:autor
1:9
2:friend
3:%d

How should I write the regexp?

使用正则表达式我需要转换此 string code> url。 p>

 &lt; a class =“navPages”href =“?mode = author&amp; amp; id = 9&amp; amp; word = friend&amp; fn =%d”&gt;%s&lt; / a&gt; 
   pre> 
 
 

要获得这样的输出格式: p>

 &lt; a class =“navPages”href =“author / 9  / friend / page /%d&gt;%s&lt; / a&gt; 
  code>  pre> 
 
 

或获得结果:
p>

  0:autor 
1:9 
2:friend 
3:%d 
  code>  pre> 
 
 

我应该如何编写正则表达式? p> DIV>

Replace all between (& or ?) and = with /:

$link = preg_replace("/[&?][^=]*=/", "/", $link);

Result: author/9/friend/%d

To get the parts in array, use the same regexp with preg_split:

$parts = preg_split("/[&?][^=]*=/", $link);

Note that first element will be empty with this approach -- result:

array(5) {
  [0]=> ""
  [1]=> "author"
  [2]=> "9"
  [3]=> "friend"
  [4]=> "%d"
}

Try something like this :

$txt = '<a class="navPages" href="?mode=author&amp;id=9&amp;word=friend&fn=%d">%s</a>';
preg_match('/^<a.*?href=(["\'])(.*?)\1.*$/', $txt, $patterns);

$data = explode('=',$patterns[2]);
$my_array=array();
foreach ($data as $key => $value) {
    $test[] = explode('&', $value);
    $my_array[]=$test[$key][0];
    unset($my_array[0]);
}

OUTPUT

Array
(
    [1] => author
    [2] => 9
    [3] => friend
    [4] => %d
)

Then use implode to get your href.

Here is a complete solution with 2 expressions (one to get the URL, one to split the link):

$link = '<a class="navPages" href="?mode=author&id=9&word=friend&fn=%d">%s</a>';

// extract the URL
preg_match('/href="([^"s]+)"/', $link, $link_match);
$url = $link_match[1];

// build the new URL and HTML link
preg_match_all('/([^\s&?=]+)=?([^\s&?=]+)?/', $url, $url_match);
$new_url = '';
foreach ($url_match[2] as $value)
    $new_url .= $value . '/';
$new_url = substr($new_url, 0, -1);
$new_link = '<a class="navPages" href="' . $new_url . '>%s</a>';

echo $new_link; // Output: <a class="navPages" href="author/9/friend/%d>%s</a>