2012-06-08 8 views
2

이것은 "-"단어 사이에 공백 문자 을 바꾸려고하는 문자열입니다.PHP 조건부 문자열 바꾸기 str_replace

"Color-red, Color-blue, Color-black"; 

하지만 그 반환 :

$mystring = "Color red, Color blue, Color black"; 
$newstring = str_replace(' ', '-', $mystring); 

내가 않는 str_replace 함수를 사용하여 달성하고자하는 무엇이다

"Color-red,-Color-blue,-Color-black"; 

내가 공백 "을하지 대체하는 조건을 필요로 추측 쉼표 뒤에 "또는"두 단어 사이에 ". 그러나 나는 잘 모른다. 어떠한 제안? , 하였다되지 않은 모든 공간 (\s)과 일치하는 negative lookbehind 사용

답변

4

(?<!,)\s

.

preg_replace("/(?<!,)\s/", '-', $mystring); 

Play with the regex here.

+2

http://www.regular-expressions.info/lookaround.html – Galen