从文本中出现的字符串填充数组

时间:2019-03-05 05:11:42

标签: javascript php regex laravel

我需要用文本中的所有“特定事件”字符串填充数组。假设我有以下文字:

  • “嗨,我叫鲍勃,我今年20岁,喜欢猫。[很多文字在这里]嗨,我叫 迪伦,我今年25岁,喜欢狗。 [这里有很多文字]嗨,我叫铃鼓,我 我今年30岁,喜欢乌龟。” [很多文字在这里]

因此,我需要一个循环来搜索“嗨,mas名称为”,并获取信息直到句点/点为止。所以我的输出将是这样的:

  • array [0]->“嗨,我叫鲍勃,我20岁,喜欢猫。”
  • array [1]->“你好,我叫Dylan,我20岁,喜欢狗。”
  • array [3]->“你好,我叫铃鼓,我今年20岁,喜欢乌龟。

直到现在,我只能从出现的位置找到索引,但无法用字符串(仅索引)填充数组。

谢谢。

ps:文本是从PHP文件中提取的,出于安全和限制的原因,我使用PHP

到目前为止,我的代码:

  $html = $file;
  $needle = "\$table->";
  $lastPos = 0;
  $positions = array();
  $positions2 = array();


  while (($lastPos = strpos($html, $needle, $lastPos))!== false) {
    $positions[] = $lastPos;
    $lastPos = $lastPos + strlen($needle);
 }

2 个答案:

答案 0 :(得分:1)

您可以使用 使用php explode()

$string = "Hi, my name is Bob, I am 20 years old and like cats. Hi, my name is Dylan, I am 25 years old and like dogs. Hi, my name is Tambourine, I am 30 years old and like turtles";
print_r (explode(".",$string));

使用正则表达式:

$string = "Hi, my name is Bob, I am 20 years old and like cats. Hi, my name is Dylan, I am 25 years old and like dogs. Hi, my name is Tambourine, I am 30 years old and like turtles";
$arr = preg_split('/[ap]\.m\.(*SKIP)(*FAIL)|\./', $string);
print_r($arr);

答案 1 :(得分:1)

您可以使用此正则表达式捕获所有句子。

[A-Z][^.]+\.?

Demo

尝试此PHP代码,

$s = "Hi, my name is Bob, I am 20 years old and like cats. Hi, my name is Dylan, I am 25 years old and like dogs. Hi, my name is Tambourine, I am 30 years old and like turtles";
preg_match_all('/[A-Z][^.]+\.?/', $s, $matches);
print_r($matches);

打印

Array
(
    [0] => Array
        (
            [0] => Hi, my name is Bob, I am 20 years old and like cats.
            [1] => Hi, my name is Dylan, I am 25 years old and like dogs.
            [2] => Hi, my name is Tambourine, I am 30 years old and like turtles
        )

)

如果您使用Javascript进行编码,则这是JS中的演示,

var s = "Hi, my name is Bob, I am 20 years old and like cats. Hi, my name is Dylan, I am 25 years old and like dogs. Hi, my name is Tambourine, I am 30 years old and like turtles"
console.log(s.match(/[A-Z][^.]+\.?/g))