douwang4374 2018-08-12 18:02
浏览 47

基于模式解析字符串

I am using php 5 to parse a string. My input string looks like the following:

{Billion is|Millions are|Trillion is} {an extremely |a| a generously | a very} { tiny|little |smallish |short |small} stage in a vast {galactic| |large|huge|tense|big |cosmic} {universe|Colosseum|planet|arena}.

Find below my minimum viable example:

<?php

function process($text)
{
    return preg_replace_callback('/\[(((?>[^\[\]]+)|(?R))*)\]/x', array(
        $this,
        'replace'
    ), $text);
}
function replace($text)
{
    $text  = $this->process($text[1]);
    $parts = explode('|', $text);
    return $parts[array_rand($parts)];
}

$text = "{Billion is|Millions are|Trillion is} {an extremely |a| a generously | a very} { tiny|little |smallish |short |small} stage in a vast {galactic| |large|huge|tense|big |cosmic} {universe|Colosseum|planet|arena}.";

$res = process($text);

echo $res;

As you can see I am trying to parse the following pattern f.ex.: {Billion is|Millions are|Trillion is} using the above regex, /\[(((?>[^\[\]]+)|(?R))*)\]/x.

As a result I am getting the same string as inputted. I would like to get as an output for example:

Billion is a very little stage in a vast huge arena.

Any suggestions what I am doing wrong?

  • 写回答

1条回答 默认 最新

  • doudi8298 2018-08-12 18:59
    关注

    How would your current code generate anything.

    1. Your regex doesn't fit. It matches nested bracketed stuff and not braced. Try{([^}]*)} for capturing everything inside {...} to $m[1] if there are no nested braces.

    2. Read about preg_replace_callback(). The second argument can not be an array.

    A working code with some further adjustments could look like this:

    function process($text) {
      return preg_replace_callback('/{([^}]*)}/', 'replace', $text);
    }
    
    function replace($m) {
      $parts = explode('|', $m[1]);
      shuffle($parts);
      return $parts[0];
    }
    
    $text = "{Billion is|Millions are|Trillion is} {an extremely|a|a generously|a very} {tiny|little|smallish|short|small} stage in a vast {galactic||large|huge|tense|big|cosmic} {universe|Colosseum|planet|arena}.";
    
    echo process($text);
    

    Billion is a generously short stage in a vast Colosseum.

    Here is a demo at eval.in

    (you can also use an anonymous function if PHP >= 5.3)

    评论

报告相同问题?

悬赏问题

  • ¥15 求指导ADS低噪放设计
  • ¥15 CARSIM前车变道设置
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存