【问题标题】:Populate array from string occurrences in text从文本中出现的字符串填充数组
【发布时间】:2019-03-05 05:11:42
【问题描述】:

我需要用文本中的所有“特定事件”字符串填充一个数组。想象一下我有文字:

  • “嗨,我叫 Bob,我今年 20 岁,喜欢猫。[这里有很多文字]嗨,我的名字是 迪伦,我今年 25 岁,喜欢狗。 [这里有很多文字]嗨,我的名字是手鼓,我 我 30 岁,喜欢乌龟”。[这里有很多文字]

所以我需要一个循环来搜索“Hi,mas name is”并获取直到句号/点的信息。所以我的输出会是这样的:

  • array[0] -> "嗨,我叫 Bob,今年 20 岁,喜欢猫。"
  • array[1] -> "嗨,我叫 Dylan,今年 20 岁,喜欢狗。"
  • array[3] -> "嗨,我叫 Tambourine,今年 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);
 }

【问题讨论】:

  • 分享你到目前为止所做的代码
  • 对不起,完成。谢谢

标签: javascript php regex laravel


【解决方案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))

【讨论】:

  • 也许我不能使用 php split 因为我只写了部分文本,在“点/句点”之后还有更多文本。但我用正则表达式 anwser 得到它。谢谢。
【解决方案2】:

你可以这样做 使用phpexplode():

$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);

【讨论】:

  • 也许我不能用 php explode 因为我只写了部分文本,在“点/句点”之后还有更多的文本。但我只是用正则表达式测试它,它完全符合我的需要。真的很谢谢你。现在我需要学习正则表达式才能完成它,但到目前为止它是完美的。
  • @JeúCasulo 欢迎,继续编码 :)
  • 顺便说一句,我正在为 Pushpesh Kumar Rajwanshi 给出“正确答案”,因为他首先回答了这个问题。但我真的很感谢你
  • @JeúCasulo 别担心兄弟
猜你喜欢
  • 1970-01-01
  • 2013-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多