Php 按单词的第一个字母搜索外部文件,并更新变量(如果存在)

Php 按单词的第一个字母搜索外部文件,并更新变量(如果存在),php,regex,Php,Regex,我想让我们用str\u replace在一个简短的.txt文件中搜索以两个不同字符开头的两个单词;例如,s和b-我可以使用找到的两个单词替换我的post变量的内容 $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

我想让我们用
str\u replace
在一个简短的
.txt
文件中搜索以两个不同字符开头的两个单词;例如,
s
b
-我可以使用找到的两个单词替换我的post变量的内容

    $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);


这样的东西应该可以用来做两个替换

$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

您的描述非常模糊,您应该在示例文本中添加您试图匹配的内容,
php
用于回送变量的短代码可能对您很方便
听起来确实像是正则表达式。但是我不确定你到底在找什么?$startID和$MAG应该是您需要查找和替换的两个单词吗?或者需要替换的两个单词的起始字符?
/s[^\s]*/g