【问题标题】:PHP How to add plus (+) character before double quotes and words without double quotes in string [closed]PHP如何在双引号和字符串中没有双引号的单词之前添加加号(+)字符[关闭]
【发布时间】:2016-04-29 17:50:39
【问题描述】:

我有以下字符串:

'this is a "text field" need "to replace"'

我想在每个非双引号单词和双引号之前添加加号(+)字符,如下所示:

'+this +is +"text field" +need +"to replace"'

有没有办法执行这样的操作?我尝试了str_replace 和正则表达式,但不知道该怎么做。

【问题讨论】:

  • 与我们分享您的尝试以及失败的原因。
  • 并告知字符串是否可以包含转义引号。

标签: php regex preg-replace preg-match str-replace


【解决方案1】:

您可以使用这种基于交替的正则表达式:

$re = '/"[^"]*"|\S+/m'; 
$str = 'this is a "text field" need "to replace"'; 

$result = preg_replace($re, '+$0', $str);
//=> +this +is +a +"text field" +need +"to replace"

RegEx Demo

"[^"]*"|\S+ 是匹配双引号文本或任何非空格单词的正则表达式,替换为 +$0,每个匹配项的前缀为 +。

【讨论】:

    【解决方案2】:

    使用这种模式:

    /(\b\w+)|("(.*?)")/
    

    Online Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-07
      • 1970-01-01
      • 2016-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-12
      • 1970-01-01
      相关资源
      最近更新 更多