首先,我将举例说明如何遍历字符串并处理字符串中的每个单词.
其次,我将解释代码的每个部分,以便您可以根据您的确切需求进行修改.
以下是如何切换超过3个字母长的每个单词的最后2个字母(如果它们是“ey”).
// Example string
$string = 'Hey they ey shay play stay nowhey';
// Create array of words splitting at spaces
$string = explode(" ", $string);
// The search and replace strings
$lookFor = "ey";
$switchTo = "ei";
// Cycle through the words
foreach($string as $key => $word)
{
// If the word has more than 3 letters
if(strlen($word) > 3)
{
// If the last two letters are what we want
if ( substr($word, -2) == $lookFor )
{
// Replace the last 2 letters of the word
$string[$key] = substr_replace($word, $switchTo, -2);
}
}
}
// Recreate string from array
$string = implode(" ", $string);
// See what we got
echo $string;
// The above will print:
// Hey thei ey sashei play nowhei
?>
我将解释每个功能,以便您可以根据自己的需要修改上述功能,因为我并不完全了解您的所有规格:
> explode()将取一个字符串并将其拆分为一个数组.第一个参数是你用它来分割它.第二个参数是字符串,因此explode(“”,$string)将通过使用空格来拆分$string.这些空格不会包含在数组中.
> foreach()将循环遍历数组的每个元素. foreach($string as $key => $word)将遍历$string的每个元素,对于每个元素,它将索引号分配给$key,元素的值(在本例中为单词)为$word .
> strlen()返回字符串的长度.
> substr()返回字符串的一部分.第一个参数是字符串,第二个参数是子字符串的开始位置,第三个可选参数是子字符串的长度.如果为负启动,则将从字符串的结尾到字符串的结尾计算开始.换句话说,substr($word,-2)返回从字符串末尾开始两个并转到字符串末尾的子字符串….最后两个字母.如果你想要前两个字母,你会使用substr($word,0,2),因为你从一开始就想要2个字母的长度.
> substr_replace()将替换字符串中的子字符串.第一个参数是整个字符串.第二个参数是您的替换子字符串.第三个参数是替换开始的地方,第四个可选参数是子字符串的长度,所以substr_replace($word,$switchTo,-2)将取$字并从倒数第二个字母开始,用$switchTo替换那里的那个.在这种情况下,我们将切换最后两个字母.如果要替换前两个字母,可以使用substr_replace($word,$switchTo,0,2)
> implode()是爆炸的对立面.它需要一个数组,并使用指定的分隔符将其形成一个字符串.