2011-03-08 8 views
2

나는 "apple|banana|peach|cherry"과 같은 문자열을 가지고 있습니다.PHP로 정규 표현식을 사용하여 텍스트 바꾸기

정규 표현식을 사용하여이 목록을 검색하고 일치하는 항목이 있으면 다른 문자열을 특정 값으로 대체하는 방법은 무엇입니까? 예를 들어

:

$input = 'There is an apple tree.'; 

변경 것과 : "There is an <fruit>apple</fruit> tree."

감사합니다, 아만다

답변

0

preg_replace function

직접 일치 할 경우, 그것은 않는 str_replace를 사용하는 것이 더 빠르다,하지만 또는 str_ireplace 같은 :

,
$text = "some apple text"; 
$fruits = explode("|", "apple|orange|peach"); 
$replace = array('replace apple', 'replace orange', 'replace peach'); 

$new = str_replace($fruits, $replace, $text); 
+0

고마워요! 정말 도움이됩니다! IMPEACH 나 SCRAPPLE과 같은 단어가 과일이라는 태그가 붙지 않게하는 방법이 있습니까? – Amanda

+1

@Amanda : 귀하의 의견에 따라 위 코드를 수정할 수 있습니다 : $ 패턴 = "/ (^ | \ W) (apple | banana | peach | cherry) (\ W | $) /"; $ replacements = "$ 1 $ 2 $ 3"; 탄환과 스크랩이 일치하지 않도록하십시오 – anubhava

8

이 시도 : 자세한 내용은

<?php 
$patterns ="/(apple|banana|peach|cherry)/"; 

$replacements = "<fruit>$1</fruit>"; 

$output = preg_replace($patterns, $replacements, "There is an apple tree."); 
echo $output; 
?> 

php manual on preg_replace

업데이트에서 찾아보세요 : @Amanda :

$patterns ="/(^|\W)(apple|banana|peach|cherry)(\W|$)/"; 
$replacements = "$1<fruit>$2</fruit>$3"; 
: 당신은이 코드를 수정할 수 있습니다 귀하의 의견에 따라 경찰

탄환과 스크랩을 맞추는 것을 피하십시오

0
$input = 'There is an apple tree.'; 
$output = preg_replace('/(apple|banana|peach|cherry)/', "<fruit>$1</fruit>", $input); 
+0

알 수 있습니다 : $ input = '사과 나무가 있습니다.'; $ output = preg_replace ('/ (사과 | 바나나 | 복숭아 | 체리) /', " $ 1", $ input); – Amanda

0

전반적으로이 방법을 사용하는 것이 좋지만 설정 및 전반적인 목표에 대해 자세히 설명해야합니다. 하지만 다음과 같이 할 수 있습니다.

$input = preg_replace('~(apple|banana|peach|cherry)~','&lt;fruit>$1&lt;/fruit>',$input); 
관련 문제