2017-09-13 70 views
0

我使用的短代碼在輸出到dom時需要封裝在錨標記中,但它已經包含似乎正在破壞代碼的錨元素。據我所知,錨元素不應該嵌套,因爲這可能會導致意外的結果,並不是很合乎邏輯。PHP在返回之前從短代碼中刪除錨元素

是否有可能在回顯到dom之前從短碼中移除錨點元素。 我會試着用一個例子來說明這一點,如果不清楚,不好意思。如果 $shortCode = do_shortcode([example]);其中[示例]的含量是

<div class="container"> 
    <h1>Heading</h1> 
    some code here 
    <a href="http://example/url">Click me</a> 
</div> 

並且這需要被包裹在一個錨定標記

echo '<a href="http://desired-link-outside-shortcode">'.$shortCode.'</a>'; 

它應該這樣在HTML DOM顯示:

<a href="http://desired-link-outside-shortcode"> 
    <div class="container"> 
    <h1>Heading</h1> 
    some code here 
    <a href="http://example/url">Click me</a> 
    </div> 
</a> 

然而,當回顯時它看起來像這樣在DOM中:

<a href="http://desired-link-outside-shortcode"> 

</a> 
<div class="container"> 
    <h1>Heading</h1> 
    some code here 
    <a href="http://example/url">Click me</a> 
</div> 

因此,我想在回聲之前刪除所有錨點元素。

我已經試過這(原諒的測試代碼)的要求,沒有工作:

$shortCode = do_shortcode([my_shortcode]); 
$startFirstAchor = strpos($shortCode, '<a href'); 
$endFirstAchor = strpos($shortCode, '</a>') + 4; 
$lengthFirst = $endFirstAchor - $startFirstAchor; 
$endShortcode = strlen($shortCode); 
$lengthSecond = $endShortcode - $endFirstAchor; 

$firstPartCode = substr($shortCode, 0, $lengthFirst); 
$secondPartCode = substr($shortCode, $endFirstAchor, $lengthSecond); 
$refinedShortCode = $firstPartCode . $secondPartCode; 

echo $refinedShortCode; 

我不是一個PHP專業所以幫助或替代方法來實現這一目標表示讚賞。

+0

爲什麼不使用來自WPs'do_shortcode'的結果錨? – lumio

+1

檢查這個鏈接,我認爲它可以幫你。 https://stackoverflow.com/questions/13052598/creating-anchor-tag-inside-anchor-tag –

回答

1

試試這個:

$dom = new DOMDocument(); 
$dom->loadHTML(do_shortcode('[my_shortcode]')); 

foreach ($dom->getElementsByTagName('a') as $node){ 
    $node->parentNode->removeChild($node); 
} 
+0

謝謝。這成功地移除了錨元素,但是dom仍然使用之前的錨元素解析短代碼。對於其他人來說,還需要'echo $ dom-> saveHTML();'。 – Shaun