【问题标题】:How to split a string from integers in php? [closed]如何在php中从整数中拆分字符串? [关闭]
【发布时间】:2017-12-06 03:07:01
【问题描述】:

我有一个这样的字符串:

$str="hello world 2 in 365 php";

我想要这个:

['hello world' , 'in' , 'php']

有什么想法吗?

【问题讨论】:

标签: php regex


【解决方案1】:

我很无聊:

$result = preg_split('/ ?\d+ ?/', $str);

在可选空格 ? 后跟 1 个或多个数字 \d+ 后跟可选空格 ? 进行拆分。如果您需要空格,只需删除 ?s。

【讨论】:

    【解决方案2】:

    这将为您完成工作(我已拆分为多个变量以确保您了解我所做的方式)

    $str = "hello world 2 in 365 php";
    $withoutNum = preg_replace('/[0-9]+/', '', $str);
    $removedDoubleWhiteSpaces = preg_replace('/\s+/', ' ', $withoutNum);
    
    $splitedArr = explode(' ', $removedDoubleWhiteSpaces);
    
    var_dump($splitedArr);
    

    编辑:

    再次阅读后,我的解决方案上面提供的解决方案是理想的解决方案。对不起。

    【讨论】:

    • 这也会将“hello”和“world”拆分为数组中的两个条目。
    • 对,刚刚看到他想要达到的目的。上面的解决方案是理想的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    • 2020-12-01
    • 2010-09-08
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    相关资源
    最近更新 更多