如果存在,则通过单词和更新var搜索外部文件



我想让我们 str_replace搜索一个简短的 .txt文件,以获取以2个特定不同字符开头的2个单词;IE。sb-我可以用2个单词来代替我的帖子变量的内容。

    $starID = //  I would like to update with found word in external file starting with 's' if exists.
    $MAG = // I would like to update with found word in external file starting with 'b' if exists.
    $pageBody = file_get_contents('./data.txt');
    $newMessage = str_replace("$starID", "$MAG", $pageBody);

<div class="display"><?php echo ($newMessage) ?></div>    

类似的东西应该有效地进行两个替换。

$starID = $_POST['starID'];
$MAG = $_POST['MAG'];
$pageBody = file_get_contents('./data.txt');
$replaceMsg = preg_replace(/s[^s]*/, $starID, $pageBody);
$newMessage = preg_replace(/b[^s]*/, $MAG, $replaceMsg);

这使用preg_replace(而不是您要求的str_replace(以及正则是将任何单词与s开头的单词匹配,直到第一个空间为止。(然后是B相同(

注意:这仅替换第一场比赛。如果您想更换S/D的多个单词,则必须在这样的结尾添加" G"来制作正则全局:

/s[^s]*/g

最新更新