Search code examples
phpregexfriendly-url

Php - parsing url to friendly (Using 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?


Solution

  • 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"
    }