Replace URL with valid ID
php, regex
Solution
This could be easily done with DOM parsing:
$html = <<<EOM
<a href="http://www.test.de/start/">Link</a>
<a href="http://www.test.de/contact/">Another Link</a>
<a href="http://www.test.de/contact/sub/">Sub Link</a>
EOM;
$dom = new DOMDocument;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('a') as $anchor) {
$href = $anchor->getAttribute('href');
if (strpos($href, 'http://www.test.de/') === 0) {
$href = '#' . strtr(trim(parse_url($href, PHP_URL_PATH), '/'), '/', '-');
$anchor->setAttribute('href', $href);
}
}
echo $dom->saveHTML();
Demo
Problem
I have a PHP String $menu with lots of links. I need to replace the href with an ID based on the link. I need to - remove the domain - remove Slashes at the begining and the end - replace Slashes in the middle with '-' This i what I have: ``` <a href="http://www.test.de/start/">Link</a> <a href="http://www.test.de/contact/">Another Link</a> <a href="http://www.test.de/contact/sub/">Sub Link</a> ``` And this what I want: ``` <a href="#start">Link</a> <a href="#contact">Another Link</a> <a href="#contact-sub">Another Link</a> ``` I tryed it with preg_replace ``` $search = array( "/http:\/\/www.test.de/", "/".preg_quote('/">', '/')."/" ); $replacement = array('#','">'); $menu = preg_replace($search,$replacement,$menu); ``` My solution looks a little bit "dirty and doesn't replace the Slashes in the middle. Any ideas for a "real" pattern to get this done?