2010-11-11 83 views
1

如果我有以下文字使用此命令的preg_match下一行問題

preg_replace('/[^#|^ ]Hello.*/m', 'Hello Again', $content); 

#Welcome to the world of Hello World Again 
#Hello World Again 
Hello World Again 

#Other Stuff 
Other 

我的輸出一直給我

#Welcome to the world of Hello World Again 
#Hello World AgainHello Again 

#Other Stuff 
Other 

我想是

#Welcome to the world of Hello World Again 
#Hello World Again 
Hello Again 

#Other Stuff 
Other 

任何想法爲什麼這是,感謝您的幫助

回答

1

使用行開始和結束匹配器分別^$,:

preg_replace('/^Hello.*$/m', 'Hello World Again', $content); 
+0

忽略'#' – 2010-11-11 20:49:41

+0

@ Angel.King.47怎麼樣,您不必忽略'#'。 '^'將表達式錨定在字符串的左側。這意味着它只會匹配以「Hello」開頭的行。 – 2010-11-11 20:51:06

+0

謝謝你的工作 – 2010-11-11 20:52:37

0

你正在取代換行符。試試這個:

preg_replace('/([^#|^ ])Hello.*/m', '\1Hello World Again', $content); 

它包括在替換字符串中由[^#|^ ]匹配的所有內容。

另外,在您的替換字符串換行:

preg_replace('/[^#|^ ]Hello.*/m', PHP_EOL . 'Hello Again', $content); 

您也可以簡化您的正則表達式:

`/^[# ]Hello.*$/' 
+0

我可不能得到正則表達式gnore結束並開始行並僅替換內部字符 – 2010-11-11 20:44:29