php 正则表达式来分割字符串

问题描述 投票:0回答:2

我有一个这样的字符串:

$str = "{It|This} part, but also {spin|rotation} the words";

我想通过正则表达式将

{It|This}
{spin|rotation}
拆分为
It, This ,spin,rotation

我需要正则表达式。

$str = "{It|This} part, but also {spin|rotation} the words";
$pattern =''; // need a pttern here
$arr = preg_split($pattern,$str);
print_r($arr);

任何帮助表示赞赏。

php regex
2个回答
2
投票

说明:

使用

preg_match_all()
匹配
{
}
之间的内容,并且通过
foreach
循环这些匹配,通过
|
展开参数,最后执行
implode()

代码..

$str = "{It|This} part, but also {spin|rotation} the words";
preg_match_all('/{(.*?)}/', $str, $matches);
foreach($matches[1] as $v)
{
    $new_val[]=explode('|',$v);
}
echo $new_val=implode(',',call_user_func_array('array_merge',$new_val));

OUTPUT :

It,This,spin,rotation

示范


0
投票

在单个正则表达式中,使用 continue 元字符

\G

/
(?:            #non-capturing group start
   \G(?!^)     #match the position immediately after a previous match but not the start of the string
   \|          #match a pipe
   |           #or
   [^{]*       #match irrelevant non-enclosure segment
   {           #match start of curly braced enclosure
   (?=[^}]+})  #lookahead for completion of the curly braced enclosure
)              #end of capturing group
\K             #forget any previously matched characters
[^}|]+         #match non-pipe, non-closing-curly-brace characters
/

实现:(演示

$str = "{It|This} part, not|that but also {spin|rotation} the words";

preg_match_all(
    '/(?:\G(?!^)\||[^{]*{(?=[^}]+}))\K[^}|]+/',
    $str,
    $m
);
var_export(implode(',', $m[0]);

$m
的输出:

array (
  0 => 
  array (
    0 => 'It',
    1 => 'This',
    2 => 'spin',
    3 => 'rotation',
  ),
)

如果您确实想用占位符中随机选择的选项替换整个占位符表达式,那么

preg_replace_callback()
是最合适的。 演示

echo preg_replace_callback(
         '/{([^}]+)}/',
         function ($m) {
             $opts = explode('|', $m[1]);
             return $opts[array_rand($opts)];
         },
         $str
     );

四种可能的输出之一:

It part, not|that but also rotation the words
© www.soinside.com 2019 - 2024. All rights reserved.