Regular expression with PHP to replace newlines - php

I am trying to replace all the \n in a json string with a double pipe ||. Here is an example of a string :
{"comment":"test1
test2
test3"}';
Here is the regex I have done :
preg_match('/"comment":"(([^\n\t\r"]*)([\n\t\r]*))+"/', $a, $t);
The result of this preg_match is
Array
(
[0] => "comment":"test1
test2
test3"
[1] =>
[2] =>
[3] =>
)
I can't find what is wrong with my regexp.
Do I need a recursive pattern (?R) ?
Thanks.

Use preg_replace function like below. I assumed that your input have balanced paranthesis.
preg_replace('~(?:"comment"[^\n]*|\G)\K\n([^{}\n]*)~', '||\1', $str)
DEMO

\n+(?=[^{]*})
You can simply use this.Replace with ||.
$re = "/\\n+(?=[^{]*})/i";
$str = "{\"comment\":\"test1\n test2\n test3\"}'";
$subst = "||";
$result = preg_replace($re, $subst, $str);

Related

Match substring in string divided by a dot

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);

How to get Variable from Regex in PHP?

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
)
)

Split string into array by regular expression without bracket

My string variable contains "[100][200][300][400]" data.
This variable should be split it into array without brackets.
Currently I can split into $matches array with regular expression, but bracket appear in array.
I have used current expression as bellow:
preg _match_all('/\[.*?\]/', $string , $matches)
why not try this:
<?php
$str = " [100][200][300][400] ";
$str = explode("][", trim($str, "[] "));
print_r($str);
exit;
This code maybe can help
$str = "[100][200][300][400]";
$str = explode("][",trim($str,'\[\]'));
Results in:
Array(
[0] => 100
[1] => 200
[2] => 300
[3] => 400
)
Use brackets to choose what part of the match you want to return.
preg_match_all('/\[(.*?)\]/', $string , $matches)

How to split a string into an array using a given regex expression

I am trying to explode / preg_split a string so that I get an array of all the values that are enclosed in ( ). I've tried the following code but I always get an empty array, I have tried many things but I cant seem to do it right
Could anyone spot what am I missing to get my desired output?
$pattern = "/^\(.*\)$/";
$string = "(y3,x3),(r4,t4)";
$output = preg_split($pattern, $string);
print_r($output);
Current output Array ( [0] => [1] => )
Desired output Array ( [0] => "(y3,x3)," [1] => "(r4,t4)" )
With preg_split() your regex should be matching the delimiters within the string to split the string into an array. Your regex is currently matching the values, and for that, you can use preg_match_all(), like so:
$pattern = "/\(.*?\)/";
$string = "(y3,x3),(r4,t4)";
preg_match_all($pattern, $string, $output);
print_r($output[0]);
This outputs:
Array
(
[0] => (y3,x3)
[1] => (r4,t4)
)
If you want to use preg_split(), you would want to match the , between ),(, but without consuming the parenthesis, like so:
$pattern = "/(?<=\)),(?=\()/";
$string = "(y3,x3),(r4,t4)";
$output = preg_split($pattern, $string);
print_r($output);
This uses a positive lookbehind and positive lookahead to find the , between the two parenthesis groups, and split on them. It also output the same as the above.
You can use a simple regex like \B,\B to split the string and improve the performance by avoiding lookahead or lookbehind regex.
\B is a non-word boundary so it will match only the , between ) and (
Here is a working example:
http://regex101.com/r/cV7bO7/1
$pattern = "/\B,\B/";
$string = "(y3,x3),(r4,t4),(r5,t5)";
$result = preg_split($pattern, $string);
$result will contain:
Array
(
[0] => (y3,x3)
[1] => (r4,t4)
[2] => (r5,t5)
)

How to split a string on comma that is NOT followed by a space?

I want the results to be:
Cats, Felines & Cougars
Dogs
Snakes
This is the closest I can get.
$string = "Cats, Felines & Cougars,Dogs,Snakes";
$result = split(',[^ ]', $string);
print_r($result);
Which results in
Array
(
[0] => Cats, Felines & Cougars
[1] => ogs
[2] => nakes
)
You can use a negative lookahead to achieve this:
,(?!\s)
In simple English, the above regex says match all commas only if it is not followed by a space (\s).
In PHP, you can use it with preg_split(), like so:
$string = "Cats, Felines & Cougars,Dogs,Snakes";
$result = preg_split('/,(?!\s)/', $string);
print_r($result);
Output:
Array
(
[0] => Cats, Felines & Cougars
[1] => Dogs
[2] => Snakes
)
the split() function has been deprecated so I'm using preg_split instead.
Here's what you want:
$string = "Cats, Felines & Cougars,Dogs,Snakes";
$result = preg_split('/,(?! )/', $string);
print_r($result);
This uses ?! to signify that we want split on a comma only when not followed by the grouped sequence.
I linked the Perl documentation on the operator since preg_split uses Perl regular expressions:
http://perldoc.perl.org/perlre.html#Look-Around-Assertions
If you want to split by a char, but want to ignore that char in case it is escaped, use a lookbehind assertion.
In this example a string will be split by ":" but "\:" will be ignored:
<?php
$string='a:b:c\:d';
$array=preg_split('#(?<!\\\)\:#',$string);
print_r($array);
?>
Results into:
Array
(
[0] => a
[1] => b
[2] => c\:d
)
http://www.php.net//manual/en/function.preg-split.php

Categories