2016-11-02 2 views
1

file_get_contents($file)을 통해 문자열을받습니다.PHP preg_match/replace가 file_get_contents 뒤에 문자 "ndash"에서 작동하지 않습니다.

"-"("-"가 아니고 HTML –)을 PHP의 preg_replace 기능으로 대체 할 수없는 이유는 무엇입니까? preg_match도 작동하지 않습니다.

예 :

$file의 출력은 "blah - blah"입니다.

$str = file_get_contents($file); $str = preg_replace('/–/', 'test', $str); echo $str;

blah test blah를 반환하지만 blah – blah을 반환해야한다.

유청은 그렇습니다. 대신 어떻게하면 ndash를 대체 할 수 있습니까?

도움 주셔서 감사합니다.

+1

시도 ''/ \ P {팔라듐}/u'' 첫째. 작동하지 않는다면 심볼이 엔티티로 문자열에 존재하고 심볼을 엔티티로 변환하기 전에'preg_replace'를 실행해야하거나 바꾸기 전에'html_entity_decode'를 사용해야 할 것입니다. 예 : 'preg_replace ('/ - /', 'test', html_entity_decode ($ str))' –

+0

주먹 코드 줄에서 명백한 구문 오류를 제외하고는 전혀 문제가 없습니다. 대부분의 경우 preg 기능을 다중 바이트 모드로 작동하도록 과부하하지 않았을 가능성이 큽니다. – arkascha

+2

온라인 PHP 편집기를 사용하여 코드를 시험해 보았지만 정상적으로 작동했습니다. http://sandbox.onlinephpfunctions.com/code/7e5bbced117493fc6a9282444197360a1ae75dde – Hearner

답변

1

파일에 긴 대시의 HTML 엔티티가 포함되어 있고 이라는 일반 텍스트를 얻으려면 먼저 html_entity_decode을 사용해야합니다.

사용

$str = preg_replace('/–/', 'test', html_entity_decode($str)); 
            ^^^^^^^^^^^^^^^^^^^^^^^^ 

PHP demo :

$str = 'blah – blah'; 
echo "Original: " . $str . "\n"; 
$str = preg_replace('/–/', 'test', html_entity_decode($str)); 
echo "Replaced: " . $str; 

출력 :

Original: blah – blah 
Replaced: blah test blah 
관련 문제