i have a string (part of a JSON data) and want to parse it in brackets [...]. here is the example :
For example
[-0.5937, 2.0734,-0.1577, 1.7941,0.2048, 1.5296] >>> [-0.5937, 2.0734], [-0.1577, 1.7941], [0.2048, 1.5296]
i wrote this PHP code works good but the problem is: when it finds the ',' and adding '], [' characters instead of it, deletes the some digits of coordinates. You can check it by adding 123456789 value after the coordinates. for example -0.5937 => -0.5937123456789 So how can i avoid deleting digits of coordinates ???
Example Code
<?php
$line = '[-0.5937, 2.0734,-0.1577, 1.7941,0.2048, 1.5296]';
$brackets = preg_replace('/\d,\S/', '], [', $line);
echo $brackets;
?>
You can do this:
$string = '[-0.5937, 2.0734,-0.1577, 1.7941,0.2048, 1.5296]';
$pattern = '~[[,]\s*(-?\d++(?>\.\d++)?)\s*,\s*(-?\d++(?>\.\d++)?)\s*(?:]|(?=(,)))~';
$result = preg_replace($pattern, '[$1, $2]$3 ', $string);
pattern details:
~ # pattern delimiter
[[,] # a [ or a ,
\s* # optional spaces
(-?\d++(?>\.\d++)?) # a number (group 1)
\s*,\s* # ,
(-?\d++(?>\.\d++)?) # (group 2)
\s*
(?: # non capturing group
] # literal ]
| # OR
(?=(,)) # a lookahead that capture the comma (group 3)
)
~
You can do this using an assertion to prevent the pattern from capturing the digit and the non-whitespace character. like so:
'/(?<=\d),(?<=\S)/'
Or, you can just change your pattern to:
'/,(?<=\S)/'
to ignore the digit character.
What I would recommend doing, however, would make your code not rely on the space before numbers. Use preg_replace_callback:
<?php
$line = '[-0.5937, 2.0734,-0.1577, 1.7941,0.2048, 1.5296]';
$i = 0;
function everyOther($matches) {
$i++;
if ($i % 2 == 1)
return ',';
else
return '], [';
}
$brackets = preg_replace_callback(
'/,/',
'everyOther',
$line);
echo $brackets;
?>
This will replace every other comma.
Related
I'm dealing with strings that contain non-comma-separated dollar values. For example:
"LOT 2 - $650000"
I need to be able to find the "$650000" and replace it with "$650,000".
The problem is, I'm a complete novice when it comes to regular expressions. I found a post that suggested this for finding numbers:
preg_match_all('!\d+!', $string, $matches);
This does successfully find both the "2" and the "650000" in my string. However, I want to make sure I only get numbers that start with "$", so I only want to get the "$650000".
Can anyone help me adapt the regular expression to get only numbers that start with "$"?
Kevin's answer is better. I went the long way around:
<?php
$dollarString = 'I would like $100000000000 more than I would like $10000000 but that is still better than $1000 and $99 problems.';
echo '<p>dollarString: ';
var_dump($dollarString);
echo '</p>';
function addCommas ($matches){
$output = [];
$number = $matches[1];
$j = 1;
for($i=strlen($number)-1; $i>=0; $i--){
array_push($output, $number[$i]);
if($j%3 == 0 && $i != 0 && $i != strlen($number)-1){array_push($output, ',');}
$j++;
}
array_push($output, '$');
$output = array_reverse($output);
return implode($output);
}
$newString = preg_replace_callback('#\$(\d+)#', 'addCommas', $dollarString);
echo '<p>newString: ';
var_dump($newString);
echo '</p>';
?>
Just add the dollar sign in your pattern and use preg_replace_callback then combine number_format. Something like this:
$string = preg_replace_callback('~\$(\d+)~', function($matches) {
return !empty($matches[1]) ? '$' . number_format($matches[1]) : null;
}, $string);
You could replace matches of the following regular expression with a comma to both confirm the presence of the dollar sign and to insert commas in the correct locations.
/(?:\$|\G)\d+?\K(?=(?:\d{3})+$)/
Start your engine!
The PCRE engine performs the following operations.
(?: : begin non-capture group
\$ : match '$'
| : or
\G : assert position at the end of the previous match
) : end non-capture group
\d+? : match 1+ digits
\K : reset starting point of match and no longer include
previously-consumed characters in reported match
(?= : begin positive lookahead
(?:\d{3}) : match 3 digits in a non-capture group
+ : execute non-capture group 1+ times
$ : match end of string
) : end positive lookahead
Try the following:
preg_match_all('!\$\d+!', $string, $matches);
This website really helped me understand how to achieve this
I have data with 2 parts with this separator |
$data = 'hello | Hello there
price | Lets talk about our support.
how are you ?| Im fine ';
And my static word is $word= 'price'
My code
$msg = array_filter(array_map('trim', explode("\n", $data)));
foreach ($msg as $singleLine) {
$partition = preg_split("/[|]+/", trim($singleLine), '2');
$part1 = strtolower($partition[0]);
}
How can I match the data? I need the result to be like this: Let's talk about our support
You may use a single regex approach:
'~^\h*price\h*\|\h*\K.*\S~m'
See the regex demo
Details
^ - start of a line (due to m modifier)
\h* - 0+ horizontal whitespace
price - your static word
\h*\|\h* - | enclosed with 0+ horizontal whitespaces
\K - match reset operator that discards the text matched so far
.*\S - 0+ chars other than line break chars, as many as possible, up to the last non-whitespace char on the line (including it).
PHP code:
if (preg_match('~^\h*' . preg_quote($word, '~') . '\h*\|\h*\K.*\S~m', $data, $match)) {
echo $match[0];
}
Wiktor's answer seems good, but you might want to turn your data into a key -> value array.
If that is the case, you may do this:
$avp = [];
if (preg_match_all('/^ \h* (?<key>[^|]+?) \h* \| \h* (?<value>[^$]+?) \h* $/mx', $data, $matches, PREG_SET_ORDER)) {
foreach ($matches as [, $key, $value]) {
$avp[$key] = $value;
}
}
$word = 'price';
echo $avp[$word]; // Lets talk about our support.
Demo: https://3v4l.org/uMBAg
To replace a whitespace with a comma and whitespace in a string I should do something like this:
$result = preg_replace('/[ ]+/', ', ', trim($value));
The result: Some, example, here, for, you
However, I only want to replace the 3d white space, so that the result would look like this:
Some example here, for you
How do I do that?
You may use something like
$value = " Some example here for you ";
$result = preg_replace('/^\S+(?:\s+\S+){2}\K\s+/', ',$0', trim($value), 1);
echo $result; // => Some example here, for you
See the PHP demo and the regex demo.
Pattern details
^ - start of string
\S+ - 1+ non-whitespaces
(?:\s+\S+){2} - two consecutive occurrences of
\s+ - 1+ whitespaces
\S+ - 1+ non-whitespaces
\K - a match reset operator
\s+ - (the $0 in the replacement pattern references this substring) 1+ whitespaces.
You can use an callback function and control when to replace:
<?php
$string = 'Some example here for you';
$i = 0;
$string = preg_replace_callback('/\s+/',function($m) use(&$i){
$i++;
if($i == 3) {
return ', ';
}
return ' ';
},$string);
echo $string;
Try this
$result = preg_replace('/^([^\s]+)\s+((?1)\s+(?1))/', '\1 \2,', trim($value));
Test it
Explanation:
^ start of string
([^\s]+) - capture everything not a space
\s+ space 1 or more
((?1)\s+(?1)) - (?1) repeat first capture group, we do this 2x with a space between, and capture that. I guess you could capture them separately, but what's the point.
The nice thing about (?{n}) is if you have to change the regex for the word capturing you only have to change it 1 time, not 3. Probably it doesn't matter here so much, but I like using it...
I have the following string:
$thetextstring = "jjfnj 948"
At the end I want to have:
echo $thetextstring; // should print jjf-nj948
So basically what am trying to do is to join the separated string then separate the first 3 letters with a -.
So far I have
$string = trim(preg_replace('/s+/', ' ', $thetextstring));
$result = explode(" ", $thetextstring);
$newstring = implode('', $result);
print_r($newstring);
I have been able to join the words, but how do I add the separator after the first 3 letters?
Use a regex with preg_replace function, this would be a one-liner:
^.{3}\K([^\s]*) *
Breakdown:
^ # Assert start of string
.{3} # Match 3 characters
\K # Reset match
([^\s]*) * # Capture everything up to space character(s) then try to match them
PHP code:
echo preg_replace('~^.{3}\K([^\s]*) *~', '-$1', 'jjfnj 948');
PHP live demo
Without knowing more about how your strings can vary, this is working solution for your task:
Pattern:
~([a-z]{2}) ~ // 2 letters (contained in capture group1) followed by a space
Replace:
-$1
Demo Link
Code: (Demo)
$thetextstring = "jjfnj 948";
echo preg_replace('~([a-z]{2}) ~','-$1',$thetextstring);
Output:
jjf-nj948
Note this pattern can easily be expanded to include characters beyond lowercase letters that precede the space. ~(\S{2}) ~
You can use str_replace to remove the unwanted space:
$newString = str_replace(' ', '', $thetextstring);
$newString:
jjfnj948
And then preg_replace to put in the dash:
$final = preg_replace('/^([a-z]{3})/', '\1-', $newString);
The meaning of this regex instruction is:
from the beginning of the line: ^
capture three a-z characters: ([a-z]{3})
replace this match with itself followed by a dash: \1-
$final:
jjf-nj948
$thetextstring = "jjfnj 948";
// replace all spaces with nothing
$thetextstring = str_replace(" ", "", $thetextstring);
// insert a dash after the third character
$thetextstring = substr_replace($thetextstring, "-", 3, 0);
echo $thetextstring;
This gives the requested jjf-nj948
You proceeding is correct. For the last step, which consists in inserting a - after the third character, you can use the substr_replace function as follows:
$thetextstring = 'jjfnj 948';
$string = trim(preg_replace('/\s+/', ' ', $thetextstring));
$result = explode(' ', $thetextstring);
$newstring = substr_replace(implode('', $result), '-', 3, false);
If you are confident enough that your string will always have the same format (characters followed by a whitespace followed by numbers), you can also reduce your computations and simplify your code as follows:
$thetextstring = 'jjfnj 948';
$newstring = substr_replace(str_replace(' ', '', $thetextstring), '-', 3, false);
Visit this link for a working demo.
Oldschool without regex
$test = "jjfnj 948";
$test = str_replace(" ", "", $test); // strip all spaces from string
echo substr($test, 0, 3)."-".substr($test, 3); // isolate first three chars, add hyphen, and concat all characters after the first three
How can I add a space after 3 and 4 digits ?
I have this numbers: +4420719480
The result needs to be: +44 2071 9480
How can I add the spaces with css or php after 4 characters?
I have tried the following code:
$str = "+4420719480";
echo chunk_split($str, 4, ' ');
But how do I add the space to the first 3 characters and then to the 4th?
You can use preg_replace
$str = '+4420719480';
echo preg_replace('~^.{3}|.{4}(?!$)~', '$0 ', $str);
pattern explanation:
~ # pattern delimiter
^.{3} # any character 3 times at the start of the string
| # OR
.{4} # any character 4 times
(?!$) # not followed by the end of the string
~ # pattern delimiter
replacement: '$0 ' (the whole pattern and a space)
Sometimes the most mundane solution will do the job just fine.
$str = "+4420719480";
$new = substr($str,0,3).' '.substr($str,3,4).' '.substr($str,7);
Using your code, you can do:
$str = "+4420719480";
echo strrev(chunk_split(strrev($str),4," "));
Kinda clunky and only works for this size of $str, but it works!