I'm trying to split a string by one or more spaces, but the below isn't working..instead it is returning the whole string as a singular array.
$str = 'I am a test';
$parts = preg_split('/\s+/', $str, PREG_SPLIT_NO_EMPTY);
print_r($parts);
Here is what it returns:
Array
(
[0] => I am a test
)
flags is the 4th parameter to preg_split, not the 3rd.
Remove PREG_SPLIT_NO_EMPTY flag: $parts = preg_split('/\s+/', $str);
Related
I have following strings:
'sample1.sample2'
'sample1.sample2.samaple3'
on so on..
I want to separate values sample1, sample2 and sample3 from this string (please note the quotation mark is there).
My code:
$matches = [];
$regex = "'(.*?)\.(.*?)'";
$string = "'dużotekstu.tekstpokropce'";
$match = preg_match(sprintf("/^%s$/", $regex), $string, $matches);
works fine only for first case.
You can do it like this
$string = "dużotekstu.tekstpokropce";
$exp = explode(".",$string);
$output = implode(",",$exp);
Output
dużotekstu,tekstpokropce
Try with this code. it may helps you.
You can trim single quotes and then a simple explode on dot:
php> $str = "'sample1.sample2.samaple3'";
php> print_r(explode('.', trim($str, "'")));
Array
(
[0] => sample1
[1] => sample2
[2] => samaple3
)
php> $str = "'sample1.sample2'";
php> print_r(explode('.', trim($str, "'")));
Array
(
[0] => sample1
[1] => sample2
)
why don't you split string using preg_split. You can refer here
Use preg_split() if it has to be a Regex:
$array = preg_split('/\./', $string);
$str = "[10:42-23:10]part1[11:30-13:20]part2"
I wish to split it into something like:
[1] 10:42-23:10
[2] part1
[3] 11:30-13:20
[4] part2
The best I managed to come up with is:
$parts = preg_split("/(\\[*\\])\w+/", $str );
But this returns
[0] => [10:42-23:10
[1] => [11:30-13:20
[2] =>
Also you can use regex in preg_match_all() instead of preg_split()
$str = "[10:42-23:10]part1[11:30-13:20]part2";
preg_match_all("/[^\[\]]+/", $str, $parts);
print_r($parts[0]);
See result in demo
Split on alternative between [ and ], and use the flag PREG_SPLIT_NO_EMPTY to not catch empty parts.
$str = "[10:42-23:10]part1[11:30-13:20]part2";
$parts = preg_split("/\[|\]/", $str, -1, PREG_SPLIT_NO_EMPTY );
print_r($parts);
Output:
Array
(
[0] => 10:42-23:10
[1] => part1
[2] => 11:30-13:20
[3] => part2
)
NB.
Thank to #WiktorStribiżew , his regex /[][]/ is much more efficient, I've some benchmark, it is about 40% faster.
$str = "[10:42-23:10]part1[11:30-13:20]part2";
$parts = preg_split("/[][]/", $str, -1, PREG_SPLIT_NO_EMPTY );
print_r($parts);
Here is the perl script I have used to do the benchmark:
#!/usr/bin/perl
use Benchmark qw(:all);
my $str = "[10:42-23:10]part1[11:30-13:20]part2";
my $count = -5;
cmpthese($count, {
'[][]' => sub {
my #parts = split(/[][]/, $str);
},
'\[|\]' => sub {
my #parts = split(/\[|\]/, $str);
},
});
Result: (2 runs)
>perl -w benchmark.pl
Rate \[|\] [][]
\[|\] 536640/s -- -40%
[][] 891396/s 66% --
>Exit code: 0
>perl -w benchmark.pl
Rate \[|\] [][]
\[|\] 530867/s -- -40%
[][] 885242/s 67% --
>Exit code: 0
Use a simple regex to match any [...] substring (\[[^][]*]) and wrap the whole pattern with a capturing group - then you can use it with preg_split and PREG_SPLIT_DELIM_CAPTURE flag to get both the captures and the substrings in between matches:
$re = '/(\[[^][]*])/';
$str = '[10:42-23:10]part1[11:30-13:20]part2';
$matches = preg_split($re, $str, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
print_r($matches);
See the PHP demo
With this approach, you may have a better control of what you match inside square brackets, as you may adjust the pattern to only match time ranges, e.g.
(\[\d{2}:\d{2}-\d{2}:\d{2}])
A [10:42-23:10]part1[11:30-13:20]part2[4][5] will get split into [10:42-23:10], part1, [11:30-13:20] and part2[4][5] (note the [4][5] are not split out).
See this regex demo
Without regex, you can use strtok:
$result = [];
$tok = strtok($str, '[]');
do {
if (!empty($tok))
$result[] = $tok;
} while (false !== $tok = strtok('[]'));
I'm trying to explode a string that has more than 1 newline. More specifically, 2 newlines, and I'm not sure how to do it. For example:
$text = "
text1
text2
text3
";
$text = explode(PHP_EOL, $text);
There would be some empty indexes in the array after this. I need to explode at 2 newlines instead of one. How do I do that?
If you are sure on how the newlines are formed (they may contain \n and/or \r), you can do it this way:
$Array = explode("\n\n", $text);
You can also trim the string, to remove newlines at the start and end:
$Array = explode("\n\n", trim($text));
This should work for you:
Just use preg_split() with the flag: PREG_SPLIT_NO_EMPTY set and explode the string with the constant PHP_EOL, e.g.
$arr = preg_split("/". PHP_EOL . "/", $text, -1, PREG_SPLIT_NO_EMPTY);
print_r($arr);
output:
Array ( [0] => text1 [1] => text2 [2] => text3 )
How can I get only the Name/Variable which is "regexed"? Like in this case the $1 or $0 in the anchor's href?
When I try to echo the $1 or $0 I get a Syntax Error because it's a Number.
At the Moment the $str is a whole Text.
function convertHashtags($str){
$regex = "/#+([a-zA-Z0-9_]+)/";
$str = preg_replace($regex, '$0', $str);
return($str);
}
Simple use preg_match before preg_replace, eg
preg_match($regex, $str, $matches);
Assuming the pattern actually matched, you should have the results in $matches[0] and $matches[1] which are the equivalent of $0 and $1 in the replace string.
FYI, the $n tokens in the replacement string are not variables though I can see how that can be confusing. They are simply references to matched groups (or the entire match in the case of $0) in the regex.
See http://php.net/manual/function.preg-replace.php#refsect1-function.preg-replace-parameters
To find multiple matches in $str, use preg_match_all(). It's almost the same only it populates $matches with a collection of matches. Use the PREG_SET_ORDER flag as the 4th argument to make the array workable. For example...
$str = ' xD #lol and #testing';
$regex = '/#(\w+)/';
preg_match_all($regex, $str, $allMatches, PREG_SET_ORDER);
print_r($allMatches);
produces...
Array
(
[0] => Array
(
[0] => #lol
[1] => lol
)
[1] => Array
(
[0] => #testing
[1] => testing
)
)
What's the right pattern to obtain something like that using preg_split.
Input:
Src.[VALUE1] + abs(Src.[VALUE2])
Output:
Array (
[0] => Src.[VALUE1]
[1] => Src.[VALUE2]
)
Instead of using preg_split, using preg_match_all makes more sense in this case:
preg_match_all('/\w+\.\[\w+\]/', $str, $matches);
$matches = $matches[0];
Result of $matches:
Array
(
[0] => Src.[VALUE1]
[1] => Src.[VALUE2]
)
This regex should be fine
Src\.\[[^\]]+\]
But instead of preg_split I'd suggest using preg_match_all
$string = 'Src.[VALUE1] + abs(Src.[VALUE2])';
$matches = array();
preg_match_all('/Src\.\[[^\]]+\]/', $string, $matches);
All matches you're looking for will be bound to $matches[0] array.
I guess preg_match_all is what you want. This works -
$string = "Src.[VALUE1] + abs(Src.[VALUE2])";
$regex = "/Src\.\[.*?\]/";
preg_match_all($regex, $string, $matches);
var_dump($matches[0]);
/*
OUTPUT
*/
array
0 => string 'Src.[VALUE1]' (length=12)
1 => string 'Src.[VALUE2]' (length=12)