如何使用php的strpos函数从数组中统计相似单词? [重复]

问题描述 投票:0回答:1

我正在使用 xpdf 将 pdf 转换为文本,然后借助正则表达式函数搜索 pdf 中冒号后的单词,然后使用 php 的 strpos 函数循环该数据并将它们存储到数据库中。它对我来说适用于单个数据。 但对于多个相同的数据,我不知道如何将此数据添加到数据库中。

我将逐步向您展示我的代码和响应:

我正在使用 xpdf 将我的 pdf 转换为文本格式,代码如下。

$text1 = (new Pdf('C:\xpdf-tools-win-4.00\bin64\pdftotext.exe'))
->setPdf($pathoffile)
->setOptions(['layout', 'layout'])
->text();
$string = $text1;

echo $string
我正在获取数据,即:

                                 In respect of Shareholders

Name:                                    xyz

Residential address:                     dublin

No of Shares:                            40

Name:                                    abc

Residential address:                     canada

No of Shares:                            2

所以,我通过上述数据得到了总共 2 名股东。现在我想将这些数据存储在我的表中

shareholders

现在,我正在使用 preg_match_all 函数将这些数据转换为数组,然后存储到数据库中。

$array = array('Name','Residential address','No of Shares');
preg_match_all($regex, $string, $matches);

使用下面的函数通过 strpos() 获取数组。

function strposa($haystack, $needles=array(), $offset=0) {
        $chr = array();
        foreach($needles as $needle) {
                $res = strpos($haystack, $needle, $offset);
                if ($res !== false) $chr[$needle] = $res;
        }
        if(empty($chr)) return false;
        return min($chr);
}

if($this->strposa($text1, $array) !== false) 
                {
                    foreach ($matches as  $value) {
                        //print_r($matches);
                        $value=array_map('trim',$value);
                        $directors_info->name= $value[0];
                        $directors_info->address= $value[1];
                        $directors_info->shares= $value[2];
                      }
                }

我的

print_r($matches)
数组显示了数据:

[0] => Array
        (
            [0] =>              xyz
            [1] =>              dublin
            [2] =>              40
            [3] =>              abc
            [4] =>              canada
            [5] =>              2
        )

但如果我有多个股东,那么它对我不起作用。我的预期输出是:

[0] => Array
            (
                [0] =>              xyz
                [1] =>              dublin
                [2] =>              40
                [0] =>              abc
                [1] =>              canada
                [2] =>              2
            )

我关心的是在表中分别存储 2 条数据和 2 行。如何实现这样的数据。提前致谢。

php arrays regex strpos pdftotext
1个回答
1
投票

不能有重复的键,因此可以创建多维数组。如果每行的数据始终存在,则可以使用大小为 3 的array_chunk

$matches = array_chunk($matches,3);

这会给你:

Array
(
    [0] => Array
        (
            [0] => xyz
            [1] => dublin
            [2] => 40
        )

    [1] => Array
        (
            [0] => abc
            [1] => canada
            [2] => 2
        )

)

演示

© www.soinside.com 2019 - 2024. All rights reserved.