PHP在保留分隔符的同时爆炸字符串 [英] PHP exploding a string while keeping delimiters

查看:83
本文介绍了PHP在保留分隔符的同时爆炸字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的项目,我需要分析不同的句子并通过确定它们是否以问号结尾来确定哪些是问题。

For my project I needed to analyze different sentences and work out which ones were questions by determining if they ended in question marks or not.

因此,我尝试使用explode但它不支持多个定界符。我暂时将所有标点符号替换为chr(1),以便无论它们以(。,!,?等...)结尾都可以爆炸所有句子。

So I tried using explode but it didn't support multiple delimiters. I temporarily replaced all punctuation to be chr(1) so that I could explode all sentences no matter what they ended with (., !, ?, etc...).

然后我需要找到每个句子的最后一个字母,但是爆炸功能删除了所有标点符号,因此我需要某种方式将其放回原处。

Then I needed to find the last letter of each sentence however the explode function had removed all of the punctuation, so I needed some way of putting it back in there.

我花了很长时间解决问题,但最终我将其破解。我在这里发布我的解决方案,以便其他人可以使用它。

It took me a long time to solve the problem but eventually I cracked it. I am posting my solution here so that others may use it.

推荐答案

这是我的函数multiExplodeKeepDelimiters。还有一个如何使用它的示例,方法是将字符串分解为不同的句子,然后查看最后一个字符是否为问号:

Here is my function, multipleExplodeKeepDelimiters. And an example of how it can be used, by exploding a string into different sentences and seeing if the last character is a question mark:

function multipleExplodeKeepDelimiters($delimiters, $string) {
    $initialArray = explode(chr(1), str_replace($delimiters, chr(1), $string));
    $finalArray = array();
    foreach($initialArray as $item) {
        if(strlen($item) > 0) array_push($finalArray, $item . $string[strpos($string, $item) + strlen($item)]);
    }
    return $finalArray;
}

$punctuation = array(".", ";", ":", "?", "!");
$string = "I am not a question. How was your day? Thank you, very nice. Why are you asking?";

$sentences = multipleExplodeKeepDelimiters($punctuation, $string);
foreach($sentences as $question) {
    if($question[strlen($question)-1] == "?") {
        print("'" . $question . "' is a question<br />");
    }
}

这篇关于PHP在保留分隔符的同时爆炸字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆