【问题标题】:How to preg_replace spaces before and after the word如何preg_replace单词前后的空格
【发布时间】:2013-06-24 01:38:45
【问题描述】:

我有什么:

$text = "
 randomword@staticwordrandomword@staticword  - False result 

 randomword@staticword    - True result 

 randomword@staticword randomword@staticword randomword@staticword  - True result 

 randomword@staticworandord@staticwordstauthello@staticwordord@staticword - False result

 randomword@ staticword  - False result

 randomword@staticword - True result 

 randomword@staticword    randomword@staticword      randomword@staticword  - True result"; 

$text = preg_replace('/(\s|^\s|\w*[a-zA-Z_]+\w*)@staticword($|\s)/', '\2<img src="image.png" border="0" alt="" /><a href="http://\1.site.com/"><b>\1</b></a>', $text); 

结果:

echo $text;

所有 TRUE 结果必须转换为链接,而不是所有 FALSE。

preg_replace 必须捕获 "something@staticword" 并将其转换为链接,前后有空格或末尾没有空格。

例子:

1 行 - 无链接 - 纯文本

2 行 hello@staticword 必须转换为链接。

问题:

我无法在 1st line4th line

上得到错误的结果

【问题讨论】:

    标签: php preg-replace


    【解决方案1】:

    你可以使用这个模式:

    $pattern = '~(?<!@)\b([^\s@]++@staticword)\b(?!@)~';
    $replacement = '<img src="image.png" alt="" /><a href="http://$1.site.com/">$1</a>';
    $text = preg_replace($pattern, $replacement, $text);
    

    (并使用 css 代替 border="0"

    【讨论】:

    • 非常感谢您节省了我失去的时间 :) !!你是正则表达式大师:p
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多