2013-05-24 2 views
2

str_ireplace를 원래 케이스를 손상시키지 않고 실행할 수 있습니까? 예컨대PHP str_ireplace 케이스를 잃지 않고

:

$txt = "Hello How Are You"; 
$a = "are"; 
$h = "hello"; 
$txt = str_ireplace($a, "<span style='background-color:#EEEE00'>".$a."</span>", $txt); 
$txt = str_ireplace($h, "<span style='background-color:#EEEE00'>".$h."</span>", $txt); 

이 모두 잘 작동하지만, 결과 출력 :

[hello] How [are] You 

대신 :

[Hello] How [Are] You 

(대괄호 색상 배경이다)

고마워. 당신이 (뿐만 아니라 메타 문자를 사용할 수있는) 단어의 전체 배열을 강조하려는 경우,

$txt = preg_replace("#\\b($a|$h)\\b#i", 
    "<span style='background-color:#EEEE00'>$1</span>", $txt); 

... 나 :

+0

또한 iireplace를 사용하는 이유는 소문자로도 변경하고 싶지만 대문자로 유지하려면 자본을 계속 유지해야한다는 것입니다. – FoxyFish

+0

내부적으로'str_ireplace'는'$ search'와'$ replace'를 소문자로 변환하여 일치하는 것을 찾습니다. 이것은 답이 아니라 문제가 발생한 이유를 설명합니다 – naththedeveloper

답변

4

당신은 아마이 찾고있는

$txt = 'Hi! How are you doing? Have some stars: * * *!'; 
$array_of_words = array('Hi!', 'stars', '*'); 

$pattern = '#(?<=^|\W)(' 
     . implode('|', array_map('preg_quote', $array_of_words)) 
     . ')(?=$|\W)#i'; 

echo preg_replace($pattern, 
     "<span style='background-color:#EEEE00'>$1</span>", $txt); 
+0

감사합니다. 5 분 안에 대답으로 받아 들일 것입니다 =) – FoxyFish

+0

@ user1483508 질문의 원래 코드도 작동합니다. 그래서'preg_replace()'를 더 느리게 사용하지 말아야합니다. 실제로 문제가 무엇인지 이해하지 못합니다. – hek2mgl

+0

@ hek2mgl : 출력에서 ​​소문자로 변경하지 않고 대문자, 소문자 및 혼합으로 작동해야하기 때문입니다. – FoxyFish

1

아름답지는 않지만 작동해야합니다.

function str_replace_alt($search,$replace,$string) 
{ 
    $uppercase_search = strtoupper($search); 
    $titleCase_search = ucwords($search); 
    $lowercase_replace = strtolower($replace); 
    $uppercase_replace = strtoupper($replace); 
    $titleCase_replace = ucwords($replace); 

    $string = str_replace($uppercase_search,$uppercase_replace,$string); 
    $string = str_replace($titleCase_search,$titleCase_replace,$string); 
    $string = str_ireplace($search,$lowercase_replace,$string); 

    return $string; 
} 
2

나는이 라인을 따라 뭔가를 원한다고 생각한다 : 표시된 단어를 찾은 다음 바꾸기를 사용한다.

function highlight($word, $text) { 
    $word_to_highlight = substr($text, stripos($text, $word), strlen($word)); 
    $text = str_ireplace($word, "<span style='background-color:#EEEE00'>".$word_to_highlight."</span>", $text); 
    return $text; 
} 
+0

고마워요, 이것 역시 제가 찾고있는 것입니다 – Solvision

+0

실제로 이것은 하나의 문자열이 여러 번 나타나는 문제 (첫 번째 형식은 원래 형식으로 유지됨)이지만 이후의 문자열은 변환됩니다. – Solvision

관련 문제