PHP将字符串替换为另一个字符串中的单词

PHP将字符串替换为另一个字符串中的单词,php,regex,Php,Regex,有两个变量: $string1 = "Source for replace"; $string2 = "String {Word2} replace"; 我需要将第二个变量中的{Word 2}替换为第一个常量中的相应单词(第二个单词将是-for)。如果{Word 2}替换的单词应该用大写字母,如果{Word}-替换一个小字母。此解决方案似乎符合您所描述的要求 $string1 = "Source for replace"; $string2 = "String {Word2} replace"

有两个变量:

$string1 = "Source for replace";
$string2 = "String {Word2} replace";

我需要将第二个变量中的{Word 2}替换为第一个常量中的相应单词(第二个单词将是-for)。如果{Word 2}替换的单词应该用大写字母,如果{Word}-替换一个小字母。

此解决方案似乎符合您所描述的要求

$string1 = "Source for replace";
$string2 = "String {Word2} replace";

//This will separate the string based on spaces
$arr1 = explode(' ', $string1);
$arr2 = explode(' ', $string2);

//Check the arrays are the same size
if( sizeof( $arr1 ) != sizeof( $arr2 ) ){
    echo "Your arrays are not the same size. This will cause error. Stop.";
    die();
}

//Find the occurence of {word2} in array 2
if( in_array('{word2}', $arr2) !== false ){
    $arr2key = array_search('{word2}', $arr2);
} else {
    $arr2key = array_search('{Word2}', $arr2);
}

//Replace the key in array 2 with the corresponding key from array 1
$arr2[$arr2key] = $arr1[$arr2key];

//Join array 2 back together again with spaces.
$string2 = implode(' ', $arr2);

echo $string2;
此代码将第二个字符串中的{word2}或{word2}替换为第一个句子中的相应单词,无论位置如何。如果两个句子的长度不相同,则会出现错误,程序将停止


今后,当您提出问题时,请更加具体,并确保包含您已经编写的任何代码。

我使用preg_match查找“{word}”及其数字。
然后我分解第一个字符串,使用str_replace并用分解字符串的索引减去1替换“{word}”。
我假设您想要计算线人类,而不是像数组一样,如果我错了,请删除-1

$string1 = "Source for replace";
$string2 = "String {Word2} replace";

Preg_match("/(\{word(\d+)\})/i", $string2, $matches);

$arr =explode(" ", $string1);

$str = str_replace($matches[1], $arr[$matches[2]-1], $string2);
Echo $str; // String for replace

如果单词位数高于$string1中的单词数,则可能会引起通知,但您可以通过以下方法解决此问题:

$arr =explode(" ", $string1);
If($matches[2] <= count($arr)){
    $str = str_replace($matches[1], $arr[$matches[2]-1], $string2);
    Echo $str;
}Else{
    Echo "there is no index " . $matches[2] . " in $string1";
}
$arr=explode(“,$string1);
如果($matches[2]我很无聊:

$words = explode(' ', $string1);

$result = preg_replace_callback('/\{(word(\d+))\}/i',
    function($m) use($words) {
        if($m[2] > count($words)) { return $m[0]; }     
        if($m[1][0] == strtoupper($m[1][0])) { return ucfirst($words[$m[2]-1]); }
        return lcfirst($words[$m[2]-1]);
    }, $string2);
  • 检查数字是否大于字数
  • 检查单词的大小写
    Word
    /
    Word
  • 从单词数组的适当索引返回单词

preg\u replace\u callback
使用一些逻辑。到目前为止,您尝试了什么?您好。您应该尝试自己编写代码。然后对不起作用的内容进行清楚的解释,并提供一个答案。阅读一个好的问题。一定要仔细阅读。