programing

php 문자열에서 모든 html 태그 제거

copysource 2023. 2. 3. 23:14
반응형

php 문자열에서 모든 html 태그 제거

데이터베이스 엔트리의 첫 번째 110자를 표시합니다.지금까지는 꽤 간단합니다.

<?php echo substr($row_get_Business['business_description'],0,110) . "..."; ?>

그러나 위 항목에는 클라이언트가 입력한 HTML 코드가 포함되어 있습니다.다음과 같이 표시됩니다.

<p class="Body1"><strong><span style="text-decoration: underline;">Ref no:</span></strong> 30001<strong></stro...

분명히 좋지 않다.

모든 html 코드를 삭제하고 싶기 때문에 DB 엔트리에서 <와 > 사이의 모든 것을 삭제한 후 처음 100자를 표시해야 합니다.

생각나는 사람?

사용하다strip_tags

$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);   //output Test paragraph. Other text

<?php echo substr(strip_tags($row_get_Business['business_description']),0,110) . "..."; ?>

PHP의 strip_tags() 함수를 사용합니다.

예를 들어 다음과 같습니다.

$businessDesc = strip_tags($row_get_Business['business_description']);
$businessDesc = substr($businessDesc, 0, 110);


print($businessDesc);

콘텐츠가 포함된 모든 HTML 태그를 PHP 문자열에서 제거합니다!

문자열에 앵커 태그가 포함되어 있고 이 태그와 콘텐츠를 삭제하려고 하면 이 방법이 도움이 됩니다.

$srting = '<a title="" href="/index.html"><b>Some Text</b></a>
Lorem Ipsum is simply dummy text of the printing and typesetting industry.';

echo strip_tags_content($srting);

function strip_tags_content($text) {

    return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text);
    
 }

출력:

Lorem Ipsum은 인쇄 및 조판업계의 단순한 더미 텍스트입니다.

다음 정규식을 사용합니다./<[^<]+?>/g

$val = preg_replace('/<[^<]+?>/g', ' ', $row_get_Business['business_description']);

$businessDesc = substr(val,0,110);

예를 들어 다음과 같이 유지하십시오.Ref no: 30001

나로서는 이것이 최선의 해결책이다.

function strip_tags_content($string) { 
    // ----- remove HTML TAGs ----- 
    $string = preg_replace ('/<[^>]*>/', ' ', $string); 
    // ----- remove control characters ----- 
    $string = str_replace("\r", '', $string);
    $string = str_replace("\n", ' ', $string);
    $string = str_replace("\t", ' ', $string);
    // ----- remove multiple spaces ----- 
    $string = trim(preg_replace('/ {2,}/', ' ', $string));
    return $string; 

}

HTML 태그에서 문자열을 제거합니다.

<?php
echo strip_tags("Hello <b>world!</b>");
?>

HTML 태그에서 문자열을 제거하지만 태그는 사용할 수 있습니다.

<?php
         echo strip_tags("Hello <b><i>world!</i></b>","<i>");
?>

larabel에서는 다음 구문을 사용할 수 있습니다.

 @php
   $description='<p>Rolling coverage</p><ul><li><a href="http://xys.com">Brexit deal: May admits she would have </a><br></li></ul></p>'
 @endphp
 {{  strip_tags($description)}}

<?php $data = "<div><p>Welcome to my PHP class, we are glad you are here</p></div>"; echo strip_tags($data); ?>

또는 데이터베이스에서 가져온 콘텐츠가 있는 경우

<?php $data = strip_tags($get_row['description']); ?> <?=substr($data, 0, 100) ?><?php if(strlen($data) > 100) { ?>...<?php } ?>

$string = <p>Awesome</p><b> Website</b><i> by Narayan</i>. Thanks for visiting enter code here;
$tags = array("p", "i");

echo preg_replace('#<(' . implode( '|', $tags) . ')(?:[^>]+)?>.*?</\1>#s', '', $string);

이거 드셔보세요

언급URL : https://stackoverflow.com/questions/14684077/remove-all-html-tags-from-php-string

반응형