将字符串分成几部分,返回所有字符

发布于 2024-11-17 03:05:34 字数 548 浏览 3 评论 0原文

我想根据以下规则打破字符串:

  1. 所有连续的字母数字字符加上点(.)必须被视为一部分
  2. 所有其他连续字符必须被视为
  3. 连续组合的 一部分12 必须被视为不同的部分,
  4. 不得返回空格

例如这个字符串:

Method(hierarchy.of.properties) = ?

应该返回这个数组:

Array
(
    [0] => Method
    [1] => (
    [2] => hierarchy.of.properties
    [3] => )
    [4] => =
    [5] => ?
)

我使用 preg_split()< 失败了/代码>,如AFAIK 它不能将模式视为要返回的元素。

有什么简单的方法来做到这一点吗?

I want to break a string according to the following rules:

  1. all consecutive alpha-numeric chars, plus the dot (.) must be treated as one part
  2. all other consecutive chars must be treated as one part
  3. consecutive combinations of 1 and 2 must be treated as different parts
  4. no whitespace must be returned

For example this string:

Method(hierarchy.of.properties) = ?

Should return this array:

Array
(
    [0] => Method
    [1] => (
    [2] => hierarchy.of.properties
    [3] => )
    [4] => =
    [5] => ?
)

I was unsuccessful with preg_split(), as AFAIK it cannot treat the pattern as an element to be returned.

Any idea for a simple way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北陌 2024-11-24 03:05:34

您可能应该使用 preg_match_all 而不是 preg_split。

preg_match_all('/[\w|\.]+|[^\w\s]+/', $string, $matches);
print_r($matches);

输出:

Array
(
    [0] => Array
        (
            [0] => Method
            [1] => (
            [2] => hierarchy.of.properties
            [3] => )
            [4] => =
            [5] => ?
        )

)

You probably should use preg_match_all over preg_split.

preg_match_all('/[\w|\.]+|[^\w\s]+/', $string, $matches);
print_r($matches);

Output:

Array
(
    [0] => Array
        (
            [0] => Method
            [1] => (
            [2] => hierarchy.of.properties
            [3] => )
            [4] => =
            [5] => ?
        )

)
阳光①夏 2024-11-24 03:05:34

这应该做你想要的:

$matches = array();
$string = "Method(hierarchy.of.properties) = ?";
foreach(preg_split('/(12|[^a-zA-Z0-9.])/', $string, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) as $match) {
    if (trim($match) != '')
        $matches[] = $match;
}

我使用了一个循环来删除所有空白匹配,因为据我所知 preg_split() 中没有适合你的功能。

This should do what you want:

$matches = array();
$string = "Method(hierarchy.of.properties) = ?";
foreach(preg_split('/(12|[^a-zA-Z0-9.])/', $string, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) as $match) {
    if (trim($match) != '')
        $matches[] = $match;
}

I used a loop to remove all whitespace matches, since as far as I know there isn't a feature in preg_split() to that for you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文