我们有一个变量$string
,它包含一些文字,如:
About 200 million CAPTCHAs are solved by humans around the world every day.
我们如何获得每个单词的2-3个最后或第一个字母(长度超过3个字母)?
将使用foreach()
检查匹配的文字:
if ('ey' is matched in the end of some word) {
replace 'ey' with 'ei' in this word;
}
感谢。
答案 0 :(得分:3)
首先,我将举例说明如何遍历字符串并处理字符串中的每个单词。
其次,我将解释代码的每个部分,以便您可以根据您的确切需要进行修改。
以下是如何切换超过3个字母的每个单词的最后2个字母(如果它们是“ey”)。
<?php
// 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(" ", $string)
将通过使用空格来分割$string
。这些空格不会包含在数组中。foreach($string as $key => $word)
将遍历$string
的每个元素,并且对于每个元素,它将索引号分配给$key
,并将元素的值(在本例中为单词)分配给$word
}。substr($word, -2)
返回从字符串末尾开始两个子字符串并返回字符串末尾的子字符串....最后两个字母。如果你想要前两个字母,你可以使用substr($word, 0, 2)
,因为你从一开始就想要一个2个字母的长度。substr_replace($word, $switchTo, -2)
将取$word
并从倒数第二个字母开始,用$switchTo
替换那里的内容。在这种情况下,我们将切换最后两个字母。如果要替换前两个字母,可以使用substr_replace($word, $switchTo, 0, 2)
答案 1 :(得分:2)
$string = 'About 200 million CAPTCHAs are solved by humans around the world every day.';
$result = array();
$words = explode(" ",$string);
foreach($words as $word){
if(strlen($word) > 3){
$result[] = substr($word,0,3); //first 3 characters, use "-3" for second paramter if you want last three
}
}
答案 2 :(得分:1)
function get_symbols($str, $reverse = false)
{
$symbols = array();
foreach (explode(' ', $str) as $word)
{
if ($reverse)
$word = strrev($word);
if (strlen($word) > 3)
$word = substr($word, 0, 3);
array_push($symbols, $word);
}
return $symbols;
}
修改强>
function change_reverse_symbol_in_word($str, $symbol, $replace_to)
{
$result = "";
foreach (explode(' ', $str) as $word)
{
$rword = $word;
if (strlen($rword) > 3)
{
$rword = substr($word, 0, -3);
}
if (!strcmp($symbol, $rword))
{
$word = substr($word, 0, strlen($word) - strlen($rword)) . $replace_to;
}
$result .= $word . " ";
}
return $result;
}
如果你想像你的问题那样使用它,你必须这样称呼它:
$string_malformed = change_reverse_symbol_in_word($str, "ey", "ei");