2011-12-04 2 views
1

길이가 2 자 이상인 모든 단어를 스팬 태그 사이의 문자열로 묶어야합니다. 모든 물음표, 구두점 등은 스팬 외부에 남겨 두어야합니다 (a-z 및 특수 문자는 ñ, á, é 등으로 만 사용해야합니다). 그래서 문자열에있는 모든 단어를 html 태그로 묶는 방법은 무엇입니까?

,이 :

<a href=http://example.com/prenda>Prenda</a> <a href=http://example.com/de>de</a> <a href=http://example.com/vestir>vestir</a> <a href=http://example.com/que>que</a> 
<a href=http://example.com/se>se</a> <a href=http://example.com/ajusta>ajusta</a>? A <a href=http://example.com/la>la</a> 
<a href=http://example.com/cintura>cintura</a> y <a href=http://example.com/llega>llega</a> 
<a href=http://example.com/generalmente>generalmente</a> <a href=http://example.com/hasta>hasta</a> <a href=http://example.com/el>el</a> <a href=http://example.com/pie>pie</a>. 

어떤 아이디어 :

Prenda de vestir que se ajusta? A la cintura y llega generalmente hasta el pie. 

이되어야 하는가? 감사!

+0

는 어쩌면 그것은 (도움 http://stackoverflow.com/q/1732348/ 596781) 먼저. –

+0

정규식을 사용하여 – kol

답변

2

사용이 :

$result = preg_replace('/\b[\p{L}\p{M}]{2,}\b/u', '<a href=http://example.com/$0>$0</a>', $subject); 

모든 문자, 모든 악센트.

이유 :

" 
\b    # Assert position at a word boundary 
[\p{L}\p{M}] # Match a single character present in the list below 
       # A character with the Unicode property “letter” (any kind of letter from any language) 
       # A character with the Unicode property “mark” (a character intended to be combined with another character (e.g. accents, umlauts, enclosing boxes, etc.)) 
    {2,}   # Between 2 and unlimited times, as many times as possible, giving back as needed (greedy) 
\b    # Assert position at a word boundary 
" 

편집 : 당신이 [열린 태그를 일치]로 시작하는 경우

$result = preg_replace_callback(
     '/\b[\p{L}\p{M}]{2,}\b/u', 
     create_function(
      '$matches', 
      'return <a href=http://example.com/strtolower($matches[0])>$matches[0]</a>;' 
     ), 
     $subject 
); 
+0

위대한 작품! 어떤 방법 으로든 예제/$ 0을 example/mb_strtolower ($ 0)와 같이 대체 할 수 있습니까? – andufo

+0

@andufo 업데이트를 확인하십시오. – FailedDev

+1

다시 한 번 감사드립니다! – andufo

1

사용이 대신은 :

\b(\w{2,})\b 

기본적으로 \b는 "단어 구분 기호"(구두점 제외하고, 단어의 시작과 끝을 일치)를 의미한다. \w은 단어 문자이지만 [0-9_] 문자를 제외하고 [a-zA-Z]으로 대체 할 수 있습니다. 그런 다음 길이가 2+ 문자를 의미하는 수량계 {2,}을 적용합니다.

대체품?

<a href="http://example.com/$1">$1</a> 

그리고 항상 example입니다. (과 예 anchor tags instead로 변환.)

+0

Hehe를 찾으십시오. 작업 코드를 작성하기 위해 연습하면서 해결책을 알려주십시오 :) – favoretti

+0

nice :) 그러나 특수 문자 (ñ)를 사용하여 잘 작동하지 않습니다. – andufo

0

다음은 예입니다 :

<? 
$without = "Prenda de vestir que se ajusta? A la cintura y llega generalmente hasta el pie."; 
$with = preg_replace("/([A-Za-z]{2,})/", "<a href=\"http://example.com/\\1\">\\1</a>", $without); 
print $with; 
?> 
+0

잘 작동하지 않습니다. 특수 문자 (ñ, á)를 사용하여 – andufo

관련 문제