为了账号安全,请及时绑定邮箱和手机立即绑定

PHP爆炸字符串,但将引号中的单词视为单个单词

PHP爆炸字符串,但将引号中的单词视为单个单词

PHP
凤凰求蛊 2019-09-24 10:58:38
如何爆炸以下字符串:Lorem ipsum "dolor sit amet" consectetur "adipiscing elit" dolor成array("Lorem", "ipsum", "dolor sit amet", "consectetur", "adipiscing elit", "dolor")以便将引号中的文本视为一个单词。这是我现在拥有的:$mytext = "Lorem ipsum %22dolor sit amet%22 consectetur %22adipiscing elit%22 dolor"$noquotes = str_replace("%22", "", $mytext");$newarray = explode(" ", $noquotes);但是我的代码将每个单词分成一个数组。如何使引号内的单词被视为一个单词?
查看完整描述

3 回答

?
梦里花落0921

TA贡献1772条经验 获得超6个赞

您可以使用preg_match_all(...):


$text = 'Lorem ipsum "dolor sit amet" consectetur "adipiscing \\"elit" dolor';

preg_match_all('/"(?:\\\\.|[^\\\\"])*"|\S+/', $text, $matches);

print_r($matches);

会产生:


Array

(

    [0] => Array

        (

            [0] => Lorem

            [1] => ipsum

            [2] => "dolor sit amet"

            [3] => consectetur

            [4] => "adipiscing \"elit"

            [5] => dolor

        )


)

如您所见,它还考虑了带引号的字符串中的转义引号。


编辑


简短说明:


"           # match the character '"'

(?:         # start non-capture group 1 

  \\        #   match the character '\'

  .         #   match any character except line breaks

  |         #   OR

  [^\\"]    #   match any character except '\' and '"'

)*          # end non-capture group 1 and repeat it zero or more times

"           # match the character '"'

|           # OR

\S+         # match a non-whitespace character: [^\s] and repeat it one or more times

并且在匹配%22而不是双引号的情况下,您可以执行以下操作:


preg_match_all('/%22(?:\\\\.|(?!%22).)*%22|\S+/', $text, $matches);


查看完整回答
反对 回复 2019-09-24
?
PIPIONE

TA贡献1829条经验 获得超9个赞

您也可以尝试此多重爆炸功能


function multiexplode ($delimiters,$string)

{


$ready = str_replace($delimiters, $delimiters[0], $string);

$launch = explode($delimiters[0], $ready);

return  $launch;

}


$text = "here is a sample: this text, and this will be exploded. this also | this one too :)";

$exploded = multiexplode(array(",",".","|",":"),$text);


print_r($exploded);


查看完整回答
反对 回复 2019-09-24
  • 3 回答
  • 0 关注
  • 425 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信