Is there way to keep delimiter while using php explode or other similar functions?
preg_split
with PREG_SPLIT_DELIM_CAPTURE
flag
For example
$parts = preg_split("/([\.\?\!\:])/", $string, -1, PREG_SPLIT_DELIM_CAPTURE);
Explode string and preserve delimiter/seperator in php
The best is to set empty separator and use positive look behind / look ahead for #
character and any character respectively:
$list = preg_split('/(?<=#)(?=.)/', $msg);
(?<=#)
is positive look behind for #
character, (?=.)
is positive look ahead for any character (this avoids generating empty string at the end).
Actually, if *
is part of separator, the following regexp would work even better (more reliably):
$list = preg_split('/(?<=#)(?=\*)/', $msg);
PHP exploding a string while keeping delimiters
Here is my function, multipleExplodeKeepDelimiters. And an example of how it can be used, by exploding a string into different sentences and seeing if the last character is a question mark:
function multipleExplodeKeepDelimiters($delimiters, $string) {
$initialArray = explode(chr(1), str_replace($delimiters, chr(1), $string));
$finalArray = array();
foreach($initialArray as $item) {
if(strlen($item) > 0) array_push($finalArray, $item . $string[strpos($string, $item) + strlen($item)]);
}
return $finalArray;
}
$punctuation = array(".", ";", ":", "?", "!");
$string = "I am not a question. How was your day? Thank you, very nice. Why are you asking?";
$sentences = multipleExplodeKeepDelimiters($punctuation, $string);
foreach($sentences as $question) {
if($question[strlen($question)-1] == "?") {
print("'" . $question . "' is a question<br />");
}
}
Empty delimiter Warning when using PHP explode() function
If dealing with multi-byte UTF-8 strings you should use:
$array = preg_split('//u', $My_String,-1, PREG_SPLIT_NO_EMPTY);
Otherwise you can just use:
$array = str_split($My_String);
The reason is noted in the manual:
str_split() will split into bytes, rather than characters when dealing with a multi-byte encoded string.
Starting from PHP version 7.4 the mbstring equivalent of str_split was added so you can now use:
$array = mb_str_split($my_string);
mb_str_split
manual page
Is there way to keep delimiter while using php explode or other similar functions?
preg_split
with PREG_SPLIT_DELIM_CAPTURE
flag
For example
$parts = preg_split("/([\.\?\!\:])/", $string, -1, PREG_SPLIT_DELIM_CAPTURE);
php explode between two delimiter and delimiter not lost
Instead of splitting, you could also match the parts that you want by matching optional horizontal whitespace chars, and then capture in group 1 as least as possible chars followed by matching [...]
For the matches get the group 1 value using $matches[1]
\h*(.*?\[[^][]*])
Regex demo | Php demo
Example code
$s = "i want to show you my youtube channel : [youtube id=12341234] and my instagram account : [instagram id=myingaccount213]";
preg_match_all("~\h*(.*?\[[^][]*])~", $s, $matches);
print_r($matches[1]);
Output
Array
(
[0] => i want to show you my youtube channel : [youtube id=12341234]
[1] => and my instagram account : [instagram id=myingaccount213]
)
Another option is making the pattern a bit more specific for youtube or instagram:
\h*(.*?\[(?:youtube|instagram)\h+id=[^][\s]+])
Regex demo
Php multiple delimiters in explode
Try about using:
$output = preg_split('/ (@|vs) /', $input);
I am trying to split/explode/preg_split a string but I want to keep the delimiter
You can use preg_match_all like so:
$matches = array();
preg_match_all('/(\/block\/[0-9]+\/page\/[0-9]+)/', '/block/2/page/2/block/3/page/4', $matches);
var_dump( $matches[0]);
Output:
array(2) {
[0]=>
string(15) "/block/2/page/2"
[1]=>
string(15) "/block/3/page/4"
}
Demo
Edit: This is the best I could do with preg_split.
$array = preg_split('#(/block/)#', '/block/2/page/2/block/3/page/4', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$result = array();
for( $i = 0, $count = count( $array); $i < $count; $i += 2)
{
$result[] = $array[$i] . $array[$i + 1];
}
It's not worth the overhead to use a regular expression if you still need to loop to prepend the delimiter. Just use explode and prepend the delimiter yourself:
$delimiter = '/block/'; $results = array();
foreach( explode( $delimiter, '/block/2/page/2/block/3/page/4') as $entry)
{
if( !empty( $entry))
{
$results[] = $delimiter . $entry;
}
}
Demo
Final Edit: Solved! Here is the solution using one regex, preg_split
, and PREG_SPLIT_DELIM_CAPTURE
$regex = '#(/block/(?:\w+/?)+(?=/block/))#';
$flags = PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY;
preg_split( $regex, '/block/2/page/2/block/3/page/4', -1, $flags);
preg_split( $regex, '/block/2/page/2/order/title/sort/asc/block/3/page/4', -1, $flags);
Output:
array(2) {
[0]=>
string(15) "/block/2/page/2"
[1]=>
string(15) "/block/3/page/4"
}
array(2) {
[0]=>
string(36) "/block/2/page/2/order/title/sort/asc"
[1]=>
string(15) "/block/3/page/4"
}
Final Demo
Related Topics
Mysql_Fetch_Array() Expects Parameter 1 to Be Resource Problem
Executing Multiple SQL Queries in One Statement with PHP
Rotate Array Elements to the Left (Move First Element to Last and Re-Index)
Mysqli Query Results to Show All Rows
Get Date Range Between Two Dates Excluding Weekends
Best Way to Get Files from a Dir Filtered by Certain Extension in PHP
PHP Passing C Struct Data Throught Socket Programming
How to Get Beanstalkd Queue to Work for PHP
The Post Method Is Not Supported for This Route. Supported Methods: Get, Head. Laravel
Strip All HTML Tags, Except Allowed
Pkill -F Doesn't Work for Process Killing
Php: Multiple SQL Queries in One MySQL_Query Statement
More Concise Way to Check to See If an Array Contains Only Numbers (Integers)