php
2017-07-07 109 views -3 likes 
-3

我有這樣的文字刪除第一個HTML標籤一個字符串

<?php 
    $example1 = '<b class="counter">1</b> This is a computer'; 
    $example2 = '<b class="counter">5</b> i have a laptop'; 
    $example3 = '<b class="counter">1</b> i need a smartphone'; 
    $example4 = 'i need a car'; // does not have <b> tag 
?> 

我在找一個PHP函數刪除字符串的一部分,從<b>開始</b>,所以結果應該是這樣的:

$example1_result = 'This is a computer'; 
$example2_result = 'i have a laptop'; 
$example3_result = 'i need a smartphone'; 
$example4_result = 'i need a car'; 
+1

use strip_tags($ example1); – Exprator

回答

0

請務必從您的「計數器」中逃脫,否則它將無法正常工作,但其他人已經使用正則表達式以更好的版本回答了您的問題。

<?php 
$example1 = "<b class=\"counter\">1</b> This is a computer"; 
$example2 = "<b class=\"counter\">5</b> i have a laptop"; 
$example3 = "<b class=\"counter\">1</b> i need a smartphone"; 

echo strip_tags($example1); //Outputs: 1 This is a computer 

$example1 = trim(substr(strstr($example1, '</b>'), strlen('</b>'))); 
echo $example1; //Outputs: This is a computer 
+0

the第二個解決方案正是我所期待的,去掉第一個包含其內容的b標籤,非常感謝。 +1 – Zaki

1

你要使用strip_tagshttp://php.net/manual/en/function.strip-tags.php

它本質上剝離,以及標籤從字符串:

<?php 
    $htmlStr = '<p>Text</p>'; 
    $str  = strip_tags($htmlStr); 

    var_dump($str); //will echo Text 
+1

你應該在回答之前理解問題。 -1 – Zaki

+1

你誤解了問題 –

+3

@Zaki,不用粗魯,也可以說你應該在提問之前進行搜索。 – Devon

0

如果您需要的結果,您可以使用substr($example, strpos($example, '</b>'))後,其中$例子是<b class="counter">1</b> This is a computer

2
preg_replace("(<([a-z]+)>.*?</\\1>)is","",$example1); 

使用這個,你要刪除的<b>標籤裏面的內容也strip_tags()將保持裏面的內容html tags

+1

啊是的,這可能會更好+1 – ThisGuyHasTwoThumbs

相關問題