我想检查连字符( - )之前是否有一些字符。
如果有东西,那么添加
<br>-
如果只有空间,什么也不做。 我对正则表达式并不擅长:(
答案 0 :(得分:2)
使用preg_replace
函数和特定正则表达式模式的解决方案:
$str = "The couch said: 'Use one-two-three combination'. -a) But it wasn't about boxing, it was about ping-pong";
$new_str = preg_replace("/(?<=\S)-/", "<br>-", $str);
print_r($new_str);
输出(作为 view-source 代码):
The couch said: 'Use one<br>-two<br>-three combination'. -a) But it wasn't about boxing, it was about ping<br>-pong
\S
- 指向非空白字符
(?<=\S)
- 正面 lookbehind 断言,确保连字符前面有一个字符
答案 1 :(得分:0)
在我的编码生涯开始时,我曾经对正则表达式感到不满,但只是花时间研究它。
您正在寻找的模式非常简单:([^\s])(-)
您可以在此测试:http://regexr.com/3f73e
[^\s]
表示匹配任何不是空格的字符(\s
表示空格)。
-
匹配连字符
()
表示捕获组。因此捕获组1将捕获连字符前的字符,捕获组2将捕获连字符。这对于替换非常重要,因为您希望维护捕获组1。