programing tip

PHP 문자열에서 모든 HTML 태그 제거

itbloger 2020. 11. 4. 07:45
반응형

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

내용이있는 PHP 문자열에서 모든 HTML 태그를 제거하십시오!

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

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

}

Just in case, fgetss() read file in a line removing/stripping all html and php tags.


In laravel you can use following syntax

 @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)}}

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

반응형