假设我有一个数组:
$myarray = (
[0] => 'Johnny likes to go to school',
[1] => 'but he only likes to go on Saturday',
[2] => 'because Saturdays are the best days',
[3] => 'unless you of course include Sundays',
[4] => 'which are also pretty good days too.',
[5] => 'Sometimes Johnny likes picking Strawberrys',
[6] => 'with his mother in the fields',
[7] => 'but sometimes he likes picking blueberries'
);保持这个数组的结构完整,我希望能够替换它中的短语,即使它们溢出到下一个或前一个字符串。另外,我不想用标点符号或案例来影响它。
示例:
字符串查找:“星期日哪也不错”
将替换为:“星期一也很不错”
在取代:
$myarray = (
[0] => 'Johnny likes to go to school',
[1] => 'but he only likes to go on Saturday',
[2] => 'because Saturdays are the best days',
[3] => 'unless you of course include Mondays',
[4] => 'which are also pretty great days too.',
[5] => 'Sometimes Johnny likes picking Strawberrys',
[6] => 'with his mother in the fields',
[7] => 'but sometimes he likes picking blueberries'
);好奇是否有一种理想的方法来做这件事。我最初的想法是,我会将数组转换成字符串,去掉标点符号和空格,计数字符,并根据字符计数替换短语。但是,它变得相当复杂,但它是一个复杂的问题。
发布于 2021-06-29 20:14:49
这是正则表达式的工作。
我使用的方法是使用一些implode (即'&')对数组进行glue。然后,通过在查找字符串中的每个字符之间插入对'&'的零或一检查,生成一个正则表达式。
我使用正则表达式来用替换字符串替换我们正在寻找的字符串的出现。然后,我使用与上面相同的分隔符(explode)将字符串d返回到数组中。
$myarray = [
0 => 'Johnny likes to go to school',
1 => 'but he only likes to go on Saturday',
2 => 'because Saturdays are the best days',
3 => 'unless you of course include Mondays',
4 => 'which are also pretty great days too.',
5 => 'Sometimes Johnny likes picking Strawberrys',
6 => 'with his mother in the fields',
7 => 'but sometimes he likes picking blueberries'
];
// preg_quote this because we're looking for the string, not for a pattern it might contain
$findstring = preg_quote("Sundays which are also pretty good");
// htmlentities this in case it contains a string of characters which happen to be an html entity
$replacestring = htmlentities("Mondays which are also pretty great");
// Combine array into one string
// We use htmlentitles to escape the ampersand, so we can use it as a sentence delimeter
$mystring = implode("&", array_map('htmlentities', $myarray));
// Turns $findString into:
// S\&?u\&?n\&?d\&?a\&?y\&?s\&? \&?w\&?h\&?i\&?c\&?h\&? \&?a\&?r\&?e\&?
// \&?a\&?l\&?s\&?o\&? \&?p\&?r\&?e\&?t\&?t\&?y\&? \&?g\&?o\&?o\&?d
$regexstring = implode("\&?", str_split($findstring));
// Johnny likes to go to school&but he only likes to go on Saturday&because Saturdays are the
// best days&unless you of course include Mondays&which are also pretty great days
// too.&Sometimes Johnny likes picking Strawberrys&with his mother in the fields&but sometimes
// he likes picking blueberries
$finalstring = preg_replace("/$regexstring/", $replacestring, $mystring);
// Break string back up into array, and return any html entities which might have existed
// at the beginning.
$replacedarray = array_map('html_entity_decode', explode("&", $finalstring));
var_dump($replacedarray);https://stackoverflow.com/questions/68184527
复制相似问题