2017-12-18 11 views
1

我有一個具有內容和錨標波紋管串刪除錨點標記:如何使用它的文本從字符串在PHP

$string = 'I am a lot of text with <a href="#">links in it</a>'; 

,我想刪除錨點標記,其文本(在它的鏈接)

我試圖與strip_tags但它仍然是錨文本字符串中,在那之後,我試圖與preg_replace這個例子:

$string = preg_replace('/<a[^>]+>([^<]+)<\/a>/i', '\1', $string); 

,但得到與strip_tags相同的結果。

我只是想刪除錨標記後「我很多文字」。

有什麼想法?

+0

如果您確切知道錨點所處的字符串位置,則可以使用'substr()'。或者你不知道? – Geshode

+2

[H̸̡̪̯ͨ͊̽̅̾Ȩ̸̡̬̩̪̯̾͛ͪ̈ͨ͊̽̅̾͘Ȩ̬̩̾͛ͪ̈͘C̷̙̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔](https://stackoverflow.com/a/1732454/2394254) – mega6382

+0

@Geshode它可以在任何地方從刺痛。 –

回答

2

怎麼樣做爆炸。爲了您上面的例子

$string = 'I am a lot of text with <a href="#">links in it</a>'; 
$string =explode("<a",$string); 
echo $string[0]; 
6

一種方法是使用通配符.*<aa>

$string = 'I am a lot of text with <a href="#">links in it</a>'; 
$string = preg_replace('/ <a.*a>/', '', $string); 
echo $string; 

在多個錨occurence的情況下,你可以使用.*?。使你的模式'/ <a.*?a>/'

0
<?php 
    function strip_tags_content($text, $tags = '', $invert = FALSE) { 

     preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si', trim($tags), $tags); 
     $tags = array_unique($tags[1]); 

     if(is_array($tags) AND count($tags) > 0) { 
     if($invert == FALSE) { 
      return preg_replace('@<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?</\1>@si', '', $text); 
     } 
     else { 
      return preg_replace('@<('. implode('|', $tags) .')\b.*?>.*?</\1>@si', '', $text); 
     } 
     } 
     elseif($invert == FALSE) { 
     return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text); 
     } 
     return $text; 
    } 

echo strip_tags_content('<a href="google.com">google.com</a>') 

    ?> 

Strip_tags_content是用來刪除所有標籤連同它的內容請參見PHP手冊的第一條評論Strip Tags

2

,你可以簡單地使用stristr()這個(DEMO):

<?php 
$string = 'I am a lot of text with <a href="#">links in it</a> Lorem Ipsum'; 
//Get part before the <a 
$stringBfr = stristr($string,'<a', true); 
//get part after and along with </a> 
$stringAftr = stristr($string,'</a>'); 
//Remove </a> 
$stringAftr = str_replace('</a>', '', $stringAftr); 
//concatenate the matched string. 
$string = $stringBfr.$stringAftr; 
var_dump($string); 
相關問題