php - 在字符串中查找短语
问题描述
我下面的代码正在运行
<?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}。
解决方案
使用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.
推荐阅读
- flutter - 如何让滚动条一直可见?
- regex - 创建多行正则表达式以查找包含某些标签并添加属性的文件中的所有 XML 结构
- docker - Docker:nginx反向代理以及如何配置多个服务(即在8080&8081上)
- c - 如何在 cooja 模拟器的 protothread 中拥有 128 位整数?
- angular - NgRx router-store 在离开当前页面时发出路由参数更改
- javascript - 当鼠标放在元素上时,如何更改 css 属性?
- java - JAVA:斐波那契递归和非递归函数
- r - k 在动物园的 rollmean/rollmedian 中使用 floor_date
- r - 在闪亮 + 传单中,每次执行渲染时都会更新 setview。我想防止这种情况
- unity3d - WebCamTexture 到字节 []?