3

我有一个带有很多链接的PHP字符串$menu 。我需要用基于链接的 ID 替换 href。

我需要

  • 删除域
  • 删除开头和结尾的斜线
  • 用'-'替换中间的斜线

这是我所拥有的:

<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>

这就是我想要的:

<a href="#start">Link</a> 
<a href="#contact">Another Link</a>
<a href="#contact-sub">Another Link</a>

我用preg_replace 试过了

$search = array(
    "/http:\/\/www.test.de/",
    "/".preg_quote('/">', '/')."/"
);
$replacement = array('#','">');
$menu = preg_replace($search,$replacement,$menu);

我的解决方案看起来有点“脏”,并没有取代中间的斜线。任何关于“真实”模式的想法来完成这个?

4

5 回答 5

6

这可以通过 DOM 解析轻松完成:

$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();

演示

于 2013-04-17T13:31:35.633 回答
1

You could use the php function parse_url(); to create an array of the url segments.

ie:

$url = 'http://www.test.de/contact/';
$urlinfo    = parse_url($url);

echo "<h2>URL INFO</h2><pre>";
print_r($urlinfo);
echo "</pre>";
// create the id to be used
$linkID = "#".str_replace('/','',$urlinfo['path']);
echo $linkID;

// OUTPUT
<h2>URL INFO</h2>
Array
(
    [scheme] => http
    [host] => www.test.de
    [path] => /contact/
)
#contact

M

于 2013-04-17T13:35:35.697 回答
0

如果域始终相同,请尝试:

str_replace("http://www.test.de/","#", $menu);
于 2013-04-17T13:31:35.660 回答
0
// Remove the domain
$menu = str_replace("http://www.text.de","",$menu);

// Remove the beginning / and add #
$menu = str_replace("\"/","\"#",$menu);

// Remove the trailing /
$menu = str_replace("/\"","\"",$menu);

// Replace all remaining / with -
$menu = str_replace("/","-",$menu);
于 2013-04-17T13:32:15.223 回答
0
  • 将固定名称域更改为#
  • 从末端修剪/
  • 用。。。来代替 -

    $domain = "http://www.test.de/"
    str_replace('/','-',trim(str_replace($domain, '#', $menu),'/');
    
于 2013-04-17T13:34:49.300 回答