0

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?

Joseph
  • 13
  • 1
  • 5

3 Answers3

2

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"
}
buff
  • 2,063
  • 10
  • 16
0

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.

SpencerX
  • 5,453
  • 1
  • 14
  • 21
0

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>
boccanegra
  • 63
  • 1
  • 6