2012-01-23 4 views
1

은 내가으로, preg_match_all와 않는 str_replace에 대한 약간의 문제가PHP 용으로, preg_match_all 및 않는 str_replace

<? 
    $source = 'hello @user_name, hello @user_name2, hello @user_name3'; 
    preg_match_all("/@[\w\d_]*/s", $source, $search); 
    foreach($search[0] as $result) { 
     $source = str_replace($result, "<b>okay</b>", $source); 
    } 

    echo $source; 
?> 

결과는 (잘못) :

hello <b>okay</b>, hello <b>okay</b>2, hello <b>okay</b>3 

올바른 결과는 다음과 같이해야합니다 :

hello <b>okay</b>, hello <b>okay</b>, hello <b>okay</b> 

누구든지 도움을받을 수 있습니까? 감사합니다. 첫 경기, @user_name는 또한 @user_name2@user_name3 (적어도 @user_name 부분)과 일치하기 때문에

답변

1

이 일어나고. 당신이 작성한 방식대로, 그것은 정상적으로 작동합니다. preg_replace()을보고 싶을 수도 있습니다. 정규식 패턴을 테스트하기 위해 나는 항상 My Regex Tester을 사용한다. (실제로는 내 것이 아니며, 그 이름이다.) 해당 사이트에서 출력 된 코드는 다음과 같습니다.

Raw Match Pattern: 
@[\w\d_]* 

Raw Replace Pattern: 
okay 

PHP Code Example: 
<?php 
$sourcestring="hello @user_name, hello @user_name2, hello @user_name3"; 
echo preg_replace('/@[\w\d_]*/s','<b>okay</b>',$sourcestring); 
?> 

$sourcestring after replacement: 
hello <b>okay</b>, hello <b>okay</b>, hello <b>okay</b> 
+0

안녕하세요, Crontab, 조언 해 주셔서 감사합니다. 나는'$ source = preg_replace ('/'.$ result. '/', ''. $ result. ' ', $ source);'결과는 동일 .. :( –

+0

'preg_match_all()'과'str_replace()'를 직렬로 사용하는 대신에'preg_replace()'를 사용하는 것을 의미했습니다 – Crontab

+0

hmm, 'preg_match_all'을 사용하지 않으면'@ '뒤에 어떤 문자열이 대체되어야하는지 모릅니다. 어떻게 되나요? –

0

preg_match_all 또는 preg_replace에는 문제가 없습니다. 문제는 str_replace와 같습니다. 검색 배열을 만든 후 첫 번째 토큰은 "user_name"값을 포함하고 str_replace 함수는 문자열에서 세 번 나오는 모든 항목을 바꿉니다. 따라서 1과 2 값은 문자열에 그대로 유지됩니다.

가 잘 작동합니다

$source = 'hello @user_name1, hello @user_name2, hello @user_name3'; 

당신이 당신의 소스를 변경하는 경우

. 그렇지 않다면 배열을 역순으로 반복해야한다.