我的下面的代码有问题,这使我发疯。我想做的是将给定数组与一个句子进行比较,然后我需要知道它们在每次出现时在句子中的位置,到目前为止,脚本仅返回一个数组,例如,Marta名称在其中的位置在句子中找到。我试图将所有结果合并到一个数组中,但此刻我有点迷茫。我希望有人可以给我一些帮助的线索。最好的祝福。
$sentence = 'Maria is Maria and Marta is Marta.';
$womennames = array("Maria","Marta");
function poswomen($chain, $words){
foreach($words as $findme){
$valida_existe = substr_count($chain,$findme);
$largo_encuentra = strlen($findme);
$posicion = array();
for($x=0; $x < strlen($chain); $x++){
$posic_x = strpos($chain, $findme, $x);
if($posic_x >= 0){
$posicion[] = $posic_x;
$x = $x+$largo_encuentra;
}
}
$posicion = array_unique($posicion);
$posicion = implode(",",$posicion);
}
return $posicion;
}
poswomen($sentence, $womennames);
print_r (poswomen($sentence, $womennames));
就像barmar所说的那样,您的位置不断重置,您需要在该位置之外进行设置,然后添加当前找到的位置以继续进行。考虑以下示例:
$sentence = 'Maria is Maria and Marta is Marta.';
$women_names = array('Maria', 'Marta');
$pos = 0;
$positions = array();
foreach($women_names as $name) {
while (($pos = strpos($sentence, $name, $pos))!== false) {
$positions[$name][] = $pos;
$pos += strlen($name);
}
$positions[$name] = implode(', ', $positions[$name]);
}
echo '<pre>';
print_r($positions);
echo '</pre>';
样本输出:
Array
(
[Maria] => 0, 9
[Marta] => 19, 28
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句