Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP preg_split with hyphen?
In PHP, you can use preg_split() to split strings at specific patterns, including hyphens. The preg_split() function uses regular expressions to define where the string should be split, giving you more control than simple explode().
Basic Hyphen Splitting
To split a string at every hyphen, use a simple pattern ?
<?php
$string = "apple-banana-cherry";
$result = preg_split('/-/', $string);
print_r($result);
?>
Array
(
[0] => apple
[1] => banana
[2] => cherry
)
Conditional Splitting with Lookahead
For more complex splitting, such as splitting only at hyphens followed by numbers, use a positive lookahead pattern ?
<?php
$values = "ABC-DEF IJKL-3553435-8990987876";
$exploded = preg_split('/-(?=[0-9])/', $values, 3);
print_r($exploded);
?>
Array
(
[0] => ABC-DEF IJKL
[1] => 3553435
[2] => 8990987876
)
How the Pattern Works
The pattern /-(?=[0-9])/ breaks down as follows:
| Component | Description |
|---|---|
- |
Matches the literal hyphen character |
(?= |
Starts a positive lookahead assertion |
[0-9] |
Matches any digit (0 through 9) |
) |
Closes the lookahead assertion |
Limiting Split Results
The third parameter in preg_split() limits the number of splits. Setting it to 3 creates at most 3 array elements ?
<?php
$text = "one-two-three-four-five";
$limited = preg_split('/-/', $text, 3);
print_r($limited);
?>
Array
(
[0] => one
[1] => two
[2] => three-four-five
)
Conclusion
Use preg_split() with lookahead patterns like /-(?=[0-9])/ for conditional splitting at hyphens. The limit parameter controls the maximum number of array elements created.
