简体   繁体   中英

How to split using the regular expressions

In order to split the given notation ,I initially used

list($pdf_platform_size, $pdf_capacity ,$pdf_accuracy) = split("[a-z-][a-z-]", $pdf_select_specification);

When the given string was say 6 x 3m - 20t - 2kg it used to seperate the given into 6x3m for $pdf_platform_size , 20t for $pdf_capacity , and 2kg for $pdf_accuracy .

But now as i upgraded to PHP 7, and split is deprecated.Using the same for preg_split() doesn't seem to work. I tried list($a,$b,$c) = preg_split("/[az-][az-]/", $x);

where $x is 6 x 3m - 20t - 2kg

But am not getting the desired result.Looking for some help here

No need for Regular Expressions if you are splitting on a - alone. Use explode instead:

[$a, $b, $c] = explode('-', '6x3m-20t-2kg');
echo $a; // 6x3m

Note: Shorthand array destructuring came with PHP 7.1

You can use explode :

list($pdf_platform_size, $pdf_capacity ,$pdf_accuracy) = array_map('trim', explode(' - ', $pdf_select_specification));

If you want the platform_size without those spaces, use trim after that.

As mentioned you can use explode , but you could also use preg_split

$x = '6 x 3m - 20t - 2kg';
list($a,$b,$c) = preg_split("/[-]/", $x);

If the space are present you may want to trim() the result

If you want values you can extract it using preg_match_all

$x = '6 x 3m - 20t - 2kg';
preg_match_all('/(\d)+[ ]*x[ ]*(\d)+m[ ]*-[ ]*(\d)+t[ ]*-[ ]*(\d)kg/', $x, $dump);
var_dump($dump);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM