【问题标题】:Filter multiple strings out of string从字符串中过滤出多个字符串
【发布时间】:2014-09-09 20:56:40
【问题描述】:

我一直在编写代码,最终确定它可以工作,但我的 PHP 处理量太大,以至于我想知道是否有更简单的方法来解决我的问题

我正在使用的数据库中充满了艺术家的曲目,以及表格中的示例:

  • composer_name = [@123:artist_display_name1] 英尺。 [@58:artist_display_name2]
  • track_title = Le Example ([@798:artist_display_name3] Remix)

[ : 之间的数字是艺术家 ID(链接到艺术家个人资料),而 : ] 之间的字符串是艺术家的显示名称(有时艺术家使用不同的名称,这就是原因)

现在的问题是如何在没有括号的情况下尽可能快地获取显示名称,但使用艺术家 ID 执行另一个操作(例如从中创建链接并将艺术家 ID 放入数据库或其他东西)

【问题讨论】:

  • 你能在你的表中添加更多的列来存储artist_iddisplay_name吗?
  • 我可以,但是涉及到很多其他表格,这基本上让事情变得困难
  • 你能把你的问题说得更准确一点吗?您在寻找数据库优化技巧吗?解析作曲家姓名和曲目标题的方法?很难知道您在寻找什么。
  • 从字符串中解析出所有显示名称的 php 脚本
  • 所以你想让[@123:artist_display_name1] ft. [@58:artist_display_name2]变成'artist_display_name1 ft. artist_display_name2'

标签: php string


【解决方案1】:

强制方法是使用带有preg_match 的正则表达式:

function renderRow($rawRow) {
    return preg_replace("/\[@([0-9]*):([^\]]*)\]/", "$2", $rawRow);
}

另一种快 10 到 20 倍的方法(根据我的快速基准测试)是一种更直接的方法 (O(N)):

function renderRow($rawRow) {
    $len = strlen($rawRow);
    $status = 0;
    for ($i = 0; $i < $len; $i++) {
        $char = $rawRow[$i];
        if ($char === '[')
            $status = 1;
        else if ($status === 1) {
            if ($char === ':')
                $status = 2;
            continue;
        }
        else if ($status === 2 && $char === ']')
            $status = 0;
        else 
            $row .= $char;
    }
    return $row;
}

【讨论】:

  • 哇,感谢@KeVin,工作起来就像一个魅力,正是我需要的,而且速度更快!顺便用了第二个功能!再次感谢!
猜你喜欢
  • 1970-01-01
  • 2021-10-03
  • 2013-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-28
  • 2021-07-23
相关资源
最近更新 更多