2011-11-23 3 views
2

HTML dom에서 substr()을 어떻게 사용할 수 있습니까? 나는 모든 html 태그를 유지하고 단지 텍스트를 짧게하고 싶다.html dom의 PHP substr

$str = '<div><a href="http://www.weather.com">Today is a nice day</a></div>'; 
$part1 = preg_replace("/<a(.*?)>(.*?)<\/a>/i",substr('\\2', 0,10),$str).'...'; 
$part2 = preg_replace("/<a(.*?)>(.*?)<\/a>/i",'\\2',$str); 
echo str_replace($part2,$part1,$str);// nothing change 
// I need <div><a href="http://www.weather.com">Today is a...</a></div> 
+0

가능한 중복 http://stackoverflow.com/questions/을 7159695/html-errors-when-truncating) – Yoshi

+0

@ Yoshi : 중복이 아님 – rabudde

+0

@rabudde 어떻게 중복되지 않습니까? html 구조를 손상시키지 않고 텍스트 노드를 잘라내는 방법을 다루고 있습니까? – Yoshi

답변

0

아마 좀 더 강력한 될 수 있지만,이 트릭 수행해야합니다

$str = '<div><a href="http://www.weather.com">Today is a nice day</a></div>'; 
echo shortenLinks($str); 

function shorten($matches) { 
    $maxlen = 10; 
    $str = $matches[2]; 
    if (strlen($str) > $maxlen) { 
     return "<" . $matches[1] . ">" . substr($str, 0, $maxlen) . "...<"; 
    } else { 
     return $matches[0]; 
    } 
} 

function shortenLinks($str) { 
    $pattern = "/<(a\s+.*)>([^<]+)</"; 
    return preg_replace_callback($pattern, "shorten", $str); 
} 
[? HTML 오류 절단 (의
+0

@answered, 구문 분석 오류 : 구문 오류, 예기치 않은 T_FUNCTION의 줄'$ callback = function ($ matches) {' –

+0

어떤 PHP 버전을 사용하고 있습니까? – regality

+0

이 (가) 이전 버전에서 작동하도록 변경 한 경우 다시 시도하십시오. – regality