Hi I need a preg_split regex that will split a string at substrings in square brackets.
This example input:
$string = 'I have a string containing [substrings] in [brackets].';
should provide this array output:
[0]= 'I have a string containing '
[1]= '[substrings]'
[2]= ' in '
[3]= '[brackets]'
[4]= '.'
After reading your revised question:
This might be what you want:
$string = 'I have a string containing [substrings] in [brackets].';
preg_split('/(\[.*?\])/', $string, null, PREG_SPLIT_DELIM_CAPTURE);
You should get:
Array
(
[0] => I have a string containing
[1] => [substrings]
[2] => in
[3] => [brackets]
[4] => .
)
Original answer:
preg_split('/%+/i', 'ot limited to 3 %%% so it can be %%%% or % or %%%%%, etc Tha');
You should get:
Array
(
[0] => ot limited to 3
[1] => so it can be
[2] => or
[3] => or
[4] => , etc Tha
)
Or if you want a mimimum of 3 then try:
preg_split('/%%%+/i', 'Not limited to 3 %%% so it can be %%%% or % or %%%%%, etc Tha');
Have a go at http://regex.larsolavtorvik.com/
I think this is what you are looking for:
$array = preg_split('/(\[.*?\])/', $string, null, PREG_SPLIT_DELIM_CAPTURE);
Related
I have a string and I need to find all occurrences of some substrings in it but I know only initials chars of substrings... Ho can I do?
Example:
$my_string = "This is a text cointaining [substring_aaa attr], [substring_bbb attr] and [substring], [substring], [substring] and I'll try to find them!";
I know all substrings begin with '[substring' and end with a space char (before attr) or ']' char, so in this example I need to find substring_aaa, substring_bbb and substring and count how many occurrences for each one of them.
The result would be an associative array with the substrings as keys and occurrerrences as values, example:
$result = array(
'substring' => 3,
'substring_aaa' => 1,
'substring_bbb' => 1
)
Match [substring and then NOT ] zero or more times and then a ]:
preg_match_all('/\[(substring[^\]]*)\]/', $my_string, $matches);
$matches[1] will yield:
Array
(
[0] => substring_aaa attr
[1] => substring_bbb attr
[2] => substring
[3] => substring
[4] => substring
)
Then you can count the values:
$result = array_count_values($matches[1]);
After rereading the question, if you don't want what comes after a space (attr in this case) then:
preg_match_all('/\[(substring[^\]\s]*)[\]\s]/', $my_string, $matches);
For which $matches[1] will yield:
Array
(
[0] => substring_aaa
[1] => substring_bbb
[2] => substring
[3] => substring
[4] => substring
)
With the array_count_values yielding:
Array
(
[substring_aaa] => 1
[substring_bbb] => 1
[substring] => 3
)
<?php
$text = "Testing text splitting\nWith a newline!";
$textArray = preg_split('/\s+/', $text, 0, PREG_SPLIT_DELIM_CAPTURE);
print_r($textArray);
The above code will output the following:
Array
(
[0] => Testing
[1] => text
[2] => splitting
[3] => With
[4] => a
[5] => newline!
)
However to my knowledge the PREG_SPLIT_DELIM_CAPTURE flag should be capturing the whitespace delimiters in the array. Am I missing something?
edit: Ok, after rereading the documentation I now understand PREG_SPLIT_DELIM_CAPTURE is not meant for this case. My desired output would be something like:
Array
(
[0] => Testing
[1] => ' '
[2] => text
[3] => ' '
[4] => splitting
[5] => '\n'
[6] => With
[7] => ' '
[8] => a
[9] => ' '
[10] => newline!
)
So if you read manual for PREG_SPLIT_DELIM_CAPTURE once again which says:
If this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well.
you will suddenly understand that expression in the delimiter pattern (in your case it is \s) will be captured (i.e added to result) only when it is in parentheses. Now, you can:
$text = "Testing text splitting\nWith a newline!";
$textArray = preg_split('/(\s+)/', $text, 0, PREG_SPLIT_DELIM_CAPTURE);
// parentheses!
print_r($textArray);
You can also use T-Regx library:
$textArray = pattern('(\s+)')->split("Testing text splitting\nWith a newline!")->inc();
Given the following string (Yes, STRING, not Array), I want to add double quotes around the names of countries.
$string = "Array ( [0] => Array ( [nicename] => Afghanistan [phonecode] => 93 ) [1] => Array ( [nicename] => United States [phonecode] => 1 )";
I want the following string:
Array ( [0] => Array ( [nicename] => "Afghanistan" [phonecode] => 93 ) [1] => Array ( [nicename] => "United States" [phonecode] => 1 )
How can I do that?
Note: This String shows only two countries, but the actual data will have more than a hundred counties.
I was thinking of doing something like
$string = preg_replace("/[[:alpha:]]/", "/\"[[:alpha:]]\"/", $string);
But the problem is that for the second argument, (1) how would PHP know what that character class [[:alpha:]] is and (2) The names of countries might contain spaces in addition to alphabetical characters.
You should really be doing this where the array is built but it can be done with a regex...
You need to capture everything after nicename until a [ or ) (e.g. if the nicename is at the end or middle of the "array").
Using something like:
(\[nicename\] => )([^\[)]+)
should accomplish that, then you need to quote the found country name:
$1"$2"
Demo: https://regex101.com/r/7TeUQu/1
this has extra spaces after the country name since whitespace were allowed there. In PHP we'll need to use preg_replace_callback and the trim function to resolve this.
$regex = '/(\[nicename\] => )([^\[)]+)/';
$replace = '$1"$2" ';
$string = 'Array ( [0] => Array ( [nicename] => Afghanistan [phonecode] => 93 ) [1] => Array ( [nicename] => United States [phonecode] => 1 )';
$string = preg_replace_callback($regex, function($match) {
return $match[1] . '"' . trim($match[2]) . '" ';
}, $string);
echo $string;
PHP Demo: https://eval.in/699678
Here you go:
$string = preg_replace('/(\[nicename\] =>) ([a-zA-Z ]+) \[/', '$1 "$2" [', $string);
I have a string variable in php, with look like "0+1.65+0.002-23.9", and I want to split in their individual values.
Ex:
0
1.65
0.002
-23.9
I Try to do with:
$keys = preg_split("/^[+-]?\\d+(\\.\\d+)?$/", $data);
but not work I expected.
Can anyone help me out? Thanks a lot in advance.
Like this:
$yourstring = "0+1.65+0.002-23.9";
$regex = '~\+|(?=-)~';
$splits = preg_split($regex, $yourstring);
print_r($splits);
Output (see live php demo):
[0] => 0
[1] => 1.65
[2] => 0.002
[3] => -23.9
Explanation
Our regex is +|(?=-). We will split on whatever it matches
It matches +, OR |...
the lookahead (?=-) matches a position where the next character is a -, allowing us to keep the -
Then we split!
Option 2 if you decide you also want to keep the + Character
(?=[+-])
This regex is one lookahead that asserts that the next position is either a plus or a minus. For my sense of esthetics it's quite a nice solution to look at. :)
Output (see online demo):
[0] => 0
[1] => +1.65
[2] => +0.002
[3] => -23.9
Reference
Lookahead and Lookbehind Zero-Length Assertions
Mastering Lookahead and Lookbehind
You could try this
$data = ' 0 1.65 0.002 -23.9';
$t = str_replace( array(' ', ' -'), array(',',',-'), trim($data) );
$ta = explode(',', $t);
print_r($ta);
Which gives you an array containing each field like so:
Array
(
[0] => 0
[1] => 1.65
[2] => 0.002
[3] => -23.9
)
RE: Your comment: The originals values are in a string variable only separated for a sign possitive or negative
$data = ' 0+1.65+0.002-23.9 ';
$t = str_replace( array('-', '+'), array(',-',',+'), trim($data) );
$ta = explode(',', $t);
print_r($ta);
which gives a similiar answer but with the correct inputs and outputs
Array
(
[0] => 0
[1] => +1.65
[2] => +0.002
[3] => -23.9
)
i want to get a particular value from string in php. Following is the string
$string = 'users://data01=[1,2]/data02=[2,3]/*';
preg_replace('/(.*)\[(.*)\](.*)\[(.*)\](.*)/', '$2', $str);
i want to get value of data01. i mean [1,2].
How can i achieve this using preg_replace?
How can solve this ?
preg_replace() is the wrong tool, I have used preg_match_all() in case you need that other item later and trimmed down your regex to capture the part of the string you are looking for.
$string = 'users://data01=[1,2]/data02=[2,3]/*';
preg_match_all('/\[([0-9,]+)\]/',$string,$match);
print_r($match);
/*
print_r($match) output:
Array
(
[0] => Array
(
[0] => [1,2]
[1] => [2,3]
)
[1] => Array
(
[0] => 1,2
[1] => 2,3
)
)
*/
echo "Your match: " . $match[1][0];
?>
This enables you to have the captured characters or the matched pattern , so you can have [1,2] or just 1,2
preg_replace is used to replace by regular expression!
I think you want to use preg_match_all() to get each data attribute from the string.
The regex you want is:
$string = 'users://data01=[1,2]/data02=[2,3]/*';
preg_match_all('#data[0-9]{2}=(\[[0-9,]+\])#',$string,$matches);
print_r($matches);
Array
(
[0] => Array
(
[0] => data01=[1,2]
[1] => data02=[2,3]
)
[1] => Array
(
[0] => [1,2]
[1] => [2,3]
)
)
I have tested this as working.
preg_replace is for replacing stuff. preg_match is for extracting stuff.
So you want:
preg_match('/(.*?)\[(.*?)\](.*?)\[(.*?)\](.*)/', $str, $match);
var_dump($match);
See what you get, and work from there.