dongxue9997 2013-07-23 01:35
浏览 58
已采纳

PHP - preg_replace()用于字符串中的单词(正则表达式模式困难)

I'm new to PHP & Arrays even though I read a lot of tutorials already. Please be understanding. :)

My intentions: For a fulltext search I'm trying to replace words within a string with custom other words contained in a list of words. It occurs to me that in order to get whole words rather than the found string as part of another word I have to use preg_replace() with a specific pattern instead of str_replace().

My problem: If a certain word is part of the list of words i.e. [apples], I'm trying to replace i.e. [Short text in a fulltext search] with i.e. [Short apples in a fulltext search]. Naturally the final string looks like [Short apples in a fullapples search] or I get some delimiter warnings.

So I'm trying to figure out a pattern for the preg_replace() function to only replace full words and not strings within combines words. And on top of that I'm pulling the word pairs out of an associative array to have a better overview of the list. This is where I'm a novice.

My trials:

$replacements = array(
                  'text' => 'apples',
                  etc…
                );

$pattern = '#\b'($searchterm)'\b#;
$searchterm = preg_replace(array_keys($replacements), $pattern, $searchterm);

echo $searchterm;

Thank you for your help!

  • 写回答

1条回答 默认 最新

  • duanbi8089 2013-07-23 01:50
    关注

    strtr may be enough for this task. .

    In order to replace full words and not strings within combines words, we simply can add blank to the head an to the end of the replace pair.

    <?php
    $replacements = array(
        'text' => 'apples',
    );
    
    $realRreplacements = array();
    foreach ($replacements as $from => $to)
    {
        $from = ' ' . $from . ' ';
        $to = ' ' . $to . ' ';
        $realRreplacements[$from] = $to;
    }
    
    $str = 'Short text in a fulltext search';
    $str = strtr($str, $realRreplacements);
    echo $str, "
    ";
    // output: Short apples in a fulltext search
    

    -

                          ************ update *************
    

    turn back to preg_replace:

    <?php
    $list = array(
        'text' => 'apples',
        'Short' => 'Long',
        'search' => 'find',
    );
    $pattens = array();
    $replacement = array();
    foreach ($list as $from => $to)
    {
        $from = '/\b' . $from . '\b/';
        $pattens[] = $from;
        $replacement[] = $to;
    }
    $str = 'Short text in a fulltext search';
    $str = preg_replace($pattens, $replacement, $str);
    echo $str, "
    "; // Long apples in a fulltext find
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解