繁体   English   中英

在字符串中查找短语

[英]Find a phrase in a string

我下面的代码正在工作

<?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上找到它。

例子:你好,我现在很好。

输出:你好,我现在{非常好|超级好|超级好}。

使用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.

你也可以这样做:

$text = 'Hello, i am really good right now.';

$match = 'really good';

$match_len = strlen($match);

$replace = array("so fine","super fine", "superb");

$pos = strpos($text, $match);

if($pos !== false){
        echo "Word Found!";
    $replace = implode("|", $replace);
    $embed = '{' . $replace . '}';
    echo $text_before . ' ' . $embed . ' ' . $text_after; 

} else{
    echo "Word Not Found!";
}

输出

你好,我现在{非常好|超级好|超级好}。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM