2011-08-27 7 views
1
$string = "WORD is the first HEJOU is the Second BOOM is the Third"; 
$sring = str_replce('???', '???<br>', $string); 
echo $string; // <br>WORD is the first <br>HEJOU is the Second <br>BOOM is the Third 

그럼 그림은 그 자체로 말합니다. 나는 모든 단어를 대문자 (대문자로 시작하는 단어가 아님)로 선택하고 그 앞의 무언가로 바꾸기를 원합니다. 어떤 아이디어?문자열에서 대문자로 단어를 찾고 바꾸는 방법은 무엇입니까?

답변

4
$string = "WORD is the first HEJOU is the Second BOOM is the Third"; 
$string = preg_replace("#\b([A-Z]+)\b#", "<br>\\1", $string); 
echo $string; 

OUTOUT
<br>WORD is the first <br>HEJOU is the Second <br>BOOM is the Third

정규 표현식 사용중인 사용할 수 있습니다 : 교체에, 그리고

\b - Match a word boundary, zero width 
[A-Z]+ - Match any combination of capital letters 
\b - Match another word boundary 
([A-Z]+) - Capture the word for use in the replacement 

\\1, replace with the captured group. 
+0

'#'문자의 용도는 무엇입니까? – user823959

+3

그것은 단락 기호입니다. '#'은 다른 문자로 바꿀 수 있습니다./일반적이다. 나는 항상 사용하는 것처럼 보입니다. # – sberry

+0

RiaD처럼 ~을 대신 사용했습니다. – sberry

1

str_replace는 다른 특정 일에 특정 문자열을 대체합니다. 당신은 말한다 preg_replace

print preg_replace('~\b[A-Z]+\b~','<br>\\0',$string); 
+0

전체 입력과 일치하는'\\ 0'이 아니라'\\ 1'에 대한 역 참조로 바꾸는 것을 의미한다고 생각합니다. – sberry

+1

@ sberry 당신은 나의 정규 표현식에서 \ 1을 볼 수 없으므로. \\ 0은 일치하는 정규 표현식입니다. 그리고 그것은 작동합니다 – RiaD

관련 문제