首页 > 解决方案 > 在字符串中查找短语

问题描述

我下面的代码正在运行

<?php
//load synonyms of words
$json_file = fopen("dict.json", "r") or die("Unable to open file!");
$js = fread($json_file, filesize("dict.json"));
$json = json_decode($js, true);
$text = "Hello my friend, today i am feeling good.";

$ar_text = explode(" ", $text);


foreach ($ar_text as $val)
{
    $rand = rand(1, 3);
    $randx = rand(1, 3);

    if ($rand == $randx)
    {

        if (array_key_exists($val, $json))
        {
            $null = "{" . $val . "|";
            $inc = $json[$val]['sinonim'];
            $i = 1;
            foreach ($inc as $siap)
            {
                $null .= $siap . "|";
                if ($i == 4) break;
                $i++;
            }
            $null .= "}";

            $text = str_replace(" $val ", " $null ", $text);

            //echo $null."<br>";

        }
        else
        {
            //echo "not found ".$val."<br>";

        }
    }

    //echo $val;

}

$text = str_replace("|}", "}", $text);
echo $text;

//echo $json['mengaras']['tag'];
?>

我使用explode逐字获取,然后用单词同义词替换,如何获得像“真的很好”这样的短语并在dict.json上找到它。

例:你好,我现在很好。

输出:你好,我现在{so fine|super fine|superb}。

标签: php

解决方案


使用str_replace()-用替换字符串替换所有出现的搜索字符串

$text = "Hello, i am really good right now.";
$find = "really good";
$replace = "so fine|super fine|superb";
$newtext= str_replace($find, $replace, $text);

输出:

Hello, i am so fine|super fine|superb right now.

推荐阅读