从数组中获取值并在字符串PHP中搜索它

时间:2017-03-26 10:47:31

标签: php

我正在尝试从以下数组中获取值:

$array = ["jack", "name", "father"];

然后我想在以下字符串中找回单词出现的位置:

$story = "Hello, my name is jack and i'm in the army. I've been in the army for 10 years. My father was also in the army.";

结果应该是:

"Hello, my name is jack and i'm in the army. My father was also in the army.";

1 个答案:

答案 0 :(得分:1)

这是获取欲望输出字符串

的自定义方式
<?php
$array = ["jack", "name", "father"];
$story = "Hello, my name is jack and i'm in the army. I've been in the army for 10 years. My father was also in the army.";
$return = [];
$splitStory = explode(".", $story);
$data = array_filter($splitStory);
//echo "<pre>";
//print_r(array_filter($splitStory));
$count = count($data);
$count2 = count($data);
for($i=0; $i < $count; $i++)
{
    for($j=0; $j < $count2; $j++)
    {
        if (strpos($data[$i], $array[$j]) !== false) {
            $return[] = $data[$i];
        } 
    }
}
$returnArray = array_unique($return);
$returnStr = implode(".", $returnArray);
echo $returnStr;  // Output : Hello, my name is jack and i'm in the army. My father was also in the army
?>
  1. array_unique()函数: - array_unique()函数从数组中删除重复值。如果有两个或多个数组值 是相同的,第一次出现将保留,另一次将 被删除。
  2. array_filter()函数: - array_filter()函数使用回调函数过滤数组的值。
  3. explode()函数: - explode()函数将字符串分解为数组。
  4. implode()函数: - implode()函数从数组元素返回一个字符串。