Explode String in PHP

烂漫一生 提交于 2019-12-06 07:35:51

Loads of different ways, but here's a RegEx as you were trying that:

$str = "123x456x78";
preg_match_all("/(\d+)x/", $str, $matches);
var_dump($matches[1]);

Output:

array(2) { [0]=> string(3) "123" [1]=> string(3) "456" }
$arr = explode("x", "123x456x78");

and then

unset($arr[2]);

if you really can't stand that poor 78.

use explode

$string='123x456x78';

$res = explode('x', $string);
if(count($res) > 0) {
    echo $res[0];
    if(count($res) > 1) {
        echo $res[1];
    }
}
$var = "123x456x78";
$array = explode("x", $var);
array_pop($array);

To explode AND remove the last result:

$string='123x456x78'; // original string

$res = explode('x', $string); // resulting array, exploded by 'x'

$c = count($res) - 1; // last key #, since array starts at 0 subtract 1

unset($res[$c]); // unset that last value, leaving you with everything else but that.

While I'm all for regular expressions, in this case it might be easier to just use PHP's array functions...

$result=array_slice(explode('x',$yourstring),0,-1);

This should work because only the last element returned by explode won't be followed by an 'x'. Not sure if explode will add an empty string as the last element if it ends on 'x' though, you might have to test that...

cartina

Use this below code to explode. It works well!

   <?php
    $str='123x456x78';
    $res=explode('x',$str);
    unset($res[count($res)-1]); // remove last array element
    print_r($res);
    ?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!