2016-03-07 12 views
1
hy my name is mike(mike) 
hi my name is julia (julia) 
martin(martin) is 27 years old. 
michael (michael) and joseph(joseph) are good friens 

我有每名內重複該行括號的名稱統一,有的用空格分隔我希望所有的括號內分隔與一些括號只。 1個空白。就這樣。獲取詞與「(」開始 - PHP正則表達式

hy my name is mike (mike) 
hi my name is julia (julia) 
martin (martin) is 27 years old. 
michael (michael) and joseph (joseph) are good friens 

我已經試過

preg_replace('/\((\S*)\)/', ' ($1)', $string); 

它的工作,我想很大的,但是一個小問題問。

它將已經分開的圓括號分開。因此,他們成爲有兩個空格

對我來說這^正則表達式/^\((\S*)\)/分開應該有但是解決這個問題它給我的錯誤。感謝您的幫助

回答

1

使用領先邊界。

\b\((\S*)\) 

演示:https://regex101.com/r/qF2kT5/1

PHP:

$string = 'hy my name is mike(mike) 
hi my name is julia (julia) 
martin(martin) is 27 years old. 
michael (michael) and joseph(joseph) are good friens'; 
echo preg_replace('/\b\((\S*)\)/', ' ($1)', $string); 

輸出:

hy my name is mike (mike) 
hi my name is julia (julia) 
martin (martin) is 27 years old. 
michael (michael) and joseph (joseph) are good friens 

^爲字符串的開頭,或線(如果m改性劑是用過的)。

+0

完美。你能幫助我嗎?它不會在第一場比賽後取代。我的意思是它像麥克(邁克)約瑟夫(約瑟夫)一樣返回。謝謝 –

+0

我不能複製那種行爲,你能提供一個這樣的例子。這是我得到的,https://eval.in/531495。 – chris85

+0

我的服務器有點小錯誤。感謝幫助 –

0

好了,你可以很容易地用這個表達式/(?<!\s)[(]/si

PHP代碼段格式化字符串。

$subject = 
    "hy my name is mike(mike) 
hi my name is julia (julia) 
martin(martin) is 27 years old. 
michael (michael) and joseph(joseph) are good friens"; 

$result = preg_replace('/(?<!\s)[(]/si', ' (', $subject); 
print($result); 

輸出:

hy my name is mike (mike) 
hi my name is julia (julia) 
martin (martin) is 27 years old. 
michael (michael) and joseph (joseph) are good friens