获得以'(' - PHP正则表达式)开头的单词

时间:2016-03-07 00:58:24

标签: php regex preg-replace

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 空格分开。就像那样。

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*)\)/应该可以解决问题,但它会给我带来错误。谢谢你的帮助

2 个答案:

答案 0 :(得分: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修饰符)。

答案 1 :(得分: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