preg replace for needed value - php

I use coordinates for shops and manually add the coordinates as lang and long to database. Sometimes by mistake, approving the coordinate.
Let me exlain by an example.
For example;
Lang is 33.4534543543 .But by mistake sometimes i push keyboard and it becomes like,
33.4534543543<
or
33.4534543543,
or
,(space)33.4534543543<
How can I get only the 33.4534543543?

preg_match_all
To find matches from a string containing multiple matches, you would use preg_match_all:
$strings = "33.4534543543<
33.4534543543,
, 33.4534543543<";
$pattern = "!(\d+\.\d+)!";
preg_match_all($pattern,$strings,$matches);
print_r($matches[0]);
Output
Array
(
[0] => 33.4534543543
[1] => 33.4534543543
[2] => 33.4534543543
)
preg_match
To find the match from a single string you could use preg_match.
$string = "33.4534543543<";
$pattern = "!(\d+\.\d+)!";
if(preg_match($pattern,$string,$match)){
print($match[0]);
}
Output
33.4534543543
preg_replace
To replace anything that is not what you want in your existing string you would use preg_replace:
$string = preg_replace('![^\d.]!','',$string);
An example:
$strings = "33.4534543543<
33.4534543543,
, 33.4534543543<";
$strings_exp = explode("\n",$strings);
$output = '';
foreach($strings_exp as $string){
$output.= "String '$string' becomes ";
$new_string = preg_replace('![^0-9.]!','',$string);
$output.= "'$new_string'\n";
}
echo $output;
output
String '33.4534543543<' becomes '33.4534543543'
String '33.4534543543,' becomes '33.4534543543'
String ', 33.4534543543<' becomes '33.4534543543'

Sound like you want to do a preg_match: http://phpfiddle.org/main/code/z6q-a1d
$old_vals = array(
'33.4534543543<',
'33.4534543543,',
', 33.4534543543<'
);
$new_vals = array();
foreach ($old_vals as $val) {
preg_match('(\d*\.?\d+)',$val, $match);
array_push($new_vals, $match[0]);
}
print_r($new_vals);
Output
Array (
[0] => 33.4534543543,
[1] => 33.4534543543,
[2] => 33.4534543543
)

Related

How do i get each expected string from a multiple string line

I dont really no how to start my steatment to output my expected result but in my achievement i have a hug string characters line example
$string = 'newboy1fineboy8badboy12 boy4andothers...';
my problem is how do i get all the boy and related characters from the string line example:
my expected result should be boy1boy8boy12boy4
Big thanks for time and impact in my solution
You can use preg_match_all and then foreach to display all data as per your requirement like below:
<?PHP
$string = 'newboy1fineboy8badboy12 boy4andothers...';
$string = preg_match_all('/boy\d+/', $string, $results);
foreach($results[0] as $val){
echo $val;
echo "<br>";
}
// Output
boy8
boy12
boy4
?>
Or if you want to get all your required data in 1 string then like below:
foreach($results[0] as $val){
$updated_string .= $val;
$updated_string .= " ";
}
echo $updated_string;
// Output
boy8 boy12 boy4
If you want to get data like runboy8 runboy12 runboy4 then you have to use str_replace like below to further update your string:
$updated_string = str_replace("boy","runboy",$string);
// Output will be runboy8 runboy12 runboy4
You can use preg_match_all() to do that:
<?php
$string = 'newboy1fineboy8badboy12 boy4andothers...';
preg_match_all('/boy\d+/', $string, $results);
print_r($results);
Then you can access the list of matching strings as $results[0]:
Array
(
[0] => Array
(
[0] => boy1
[1] => boy8
[2] => boy12
[3] => boy4
)
)

Shortest way to get matched patterns from a string with regex

I have pretty long string to parse, that looks like that (part of it)
$string = 'FIRM_ID = MC0356400000; TAG = EQTV; CURR_CODE = SUR; CLIENT_CODE = FR334; LIMIT_KIND = 1; OPEN_BALANCE = 4822.84; OPEN_LIMIT = 0.00; LEVERAGE = 0;'
I need to get values for php variables from that string, which I do with preg_match:
preg_match("/FIRM_ID = (.*?);/", $string, $m);
$firm_id = trim($m[1]);
preg_match("/CLIENT_CODE = (.*?);/", $string, $m);
$client_code = trim($m[1]);
... and so on
I was wondering is there a way to do the same in one line? May be with preg_replace or other functions, so I would not have to declare $m variable first and then take out from that [1] element.
So the code supposed to look like
$firm_id = somefunction($string);
$client_code = somefunction($string);
Its not practical question, more theoretical. I know how to get result that I need, I want to know if there is a simpler and more elegant way.
Thanks.
If you remove spaces and replace ; with &, you can do this:
parse_str(str_replace([' ', ';'], ['', '&'], $string), $result);
Which yields an easy to use associative array:
Array
(
[FIRM_ID] => MC0356400000
[TAG] => EQTV
[CURR_CODE] => SUR
[CLIENT_CODE] => FR334
[LIMIT_KIND] => 1
[OPEN_BALANCE] => 4822.84
[OPEN_LIMIT] => 0.00
[LEVERAGE] => 0
)
So just echo $result['FIRM_ID'];
Match and capture key-value pairs and then combine into an array:
$re = '/(\w+)\s*=\s*([^;]*)/';
$str = 'FIRM_ID = MC0356400000; TAG = EQTV; CURR_CODE = SUR; CLIENT_CODE = FR334; LIMIT_KIND = 1; OPEN_BALANCE = 4822.84; OPEN_LIMIT = 0.00; LEVERAGE = 0;';
preg_match_all($re, $str, $matches);
print_r(array_combine($matches[1],$matches[2]));
See the PHP demo, result:
Array
(
[FIRM_ID] => MC0356400000
[TAG] => EQTV
[CURR_CODE] => SUR
[CLIENT_CODE] => FR334
[LIMIT_KIND] => 1
[OPEN_BALANCE] => 4822.84
[OPEN_LIMIT] => 0.00
[LEVERAGE] => 0
)
The regex is
/(\w+)\s*=\s*([^;]*)/
See is demo online.
Details:
(\w+) - Group 1: one or more word chars
\s*=\s* - a = enclosed with optional whitespace(s)
([^;]*) - Group 2: zero or more chars other than ;.
To "initialize" the variables each at a time, you may use a
$var_name = 'FIRM_ID';
$re = '/' . $var_name . '\s*=\s*\K[^;]*/';
$str = 'FIRM_ID = MC0356400000; TAG = EQTV; CURR_CODE = SUR; CLIENT_CODE = FR334; LIMIT_KIND = 1; OPEN_BALANCE = 4822.84; OPEN_LIMIT = 0.00; LEVERAGE = 0;';
preg_match($re, $str, $m);
print_r($m);
See the PHP demo.
The \K is the match reset operator that omits all text matched so far within the current match iteration.
You can also use list function after preg_match_all :
preg_match_all('/(\w[\w-]*)\h*=\h*([^;\h]+);/', $string, $matches);
list($firmId, $tag, $currCode, $clientCode, $limitKind, $openBalance, $openLimit, $leverage) = $matches[2];
echo $firmId;
//=> MC0356400000
echo $tag;
//=> EQTV
echo $clientCode;
//=> FR334
echo $openBalance;
//=> 4822.84

PHP Regex for a specific numeric value inside a comma-delimited integer number string

I am trying to get the integer on the left and right for an input from the $str variable using REGEX. But I keep getting the commas back along with the integer. I only want integers not the commas. I have also tried replacing the wildcard . with \d but still no resolution.
$str = "1,2,3,4,5,6";
function pagination()
{
global $str;
// Using number 4 as an input from the string
preg_match('/(.{2})(4)(.{2})/', $str, $matches);
echo $matches[0]."\n".$matches[1]."\n".$matches[1]."\n".$matches[1]."\n";
}
pagination();
How about using a CSV parser?
$str = "1,2,3,4,5,6";
$line = str_getcsv($str);
$target = 4;
foreach($line as $key => $value) {
if($value == $target) {
echo $line[($key-1)] . '<--low high-->' . $line[($key+1)];
}
}
Output:
3<--low high-->5
or a regex could be
$str = "1,2,3,4,5,6";
preg_match('/(\d+),4,(\d+)/', $str, $matches);
echo $matches[1]."<--low high->".$matches[2];
Output:
3<--low high->5
The only flaw with these approaches is if the number is the start or end of range. Would that ever be the case?
I believe you're looking for Regex Non Capture Group
Here's what I did:
$regStr = "1,2,3,4,5,6";
$regex = "/(\d)(?:,)(4)(?:,)(\d)/";
preg_match($regex, $regStr, $results);
print_r($results);
Gives me the results:
Array ( [0] => 3,4,5 [1] => 3 [2] => 4 [3] => 5 )
Hope this helps!
Given your function name I am going to assume you need this for pagination.
The following solution might be easier:
$str = "1,2,3,4,5,6,7,8,9,10";
$str_parts = explode(',', $str);
// reset and end return the first and last element of an array respectively
$start = reset($str_parts);
$end = end($str_parts);
This prevents your regex from having to deal with your numbers getting into the double digits.

Use regular expression to extract attribute value for custom tag

Thanks for taking a look at this. I'm using PHP. I have a string like so:
[QUOTE="name: Max-Fischer, post: 486662533, member: 123"]I don't so much dance as rhythmically convulse.[/QUOTE]
And I want to pull out the values in the quotes and create an associative array like so:
["name" => "Max-Fischer", "post" => "486662533", "member" => "123"]
Then, I would like to remove the opening and closing [QUOTE] tags and replace them with custom HTML like so:
<blockquote>Max-Fischer wrote: I don't so much dance as rhythmically convulse.</blockquote>
So the main problem is creating the preg_match() or preg_replace() to handle first: grabbing the values out in an array, and second: removing the tags and replacing them with my custom content. I can figure out how to use the array to create the custom HTML, I just can't figure how to use regular expressions well enough to achieve it.
I tried a match like this to get the attribute values:
/(\S+)=[\"\']?((?:.(?![\"\']?\s+(?:\S+)=|[>\"\']))+.)[\"\']?/
But this only returns:
[QUOTE
And that's not even addressing how to put the values (if I can get them) into an array.
Thanks in advance for your time.
Cheers.
If the tag you're looking for is always going to be quote, then perhaps something a little simpler is possible:
$s ='"[QUOTE="name: Max-Fischer, post: 486662533, member: 123"]I don\'t so much dance as rhythmically convulse.[/QUOTE]';
$r = '/\[QUOTE="(.*?)"\](.*)\[\/QUOTE\]/';
$m = array();
$arr = array();
preg_match($r, $s, $m);
// m[0] = the initial string
// m[1] = the string of attributes
// m[2] = the quote itself
foreach(explode(',', $m[1]) as $valuepair) { // split the attributes on the comma
preg_match('/\s*(.*): (.*)/', $valuepair, $mm);
// mm[0] = the attribute pairing
// mm[1] = the attribute name
// mm[2] = the attribute value
$arr[$mm[1]] = $mm[2];
}
print_r($arr);
print $m[2] . "\n";
this gives the following output:
Array
(
[name] => Max-Fischer
[post] => 486662533
[member] => 123
)
I don't so much dance as rhythmically convulse.
If you want to handle the case where there is more than one quote in the string, we can do this by modifying the regex to be slightly less greedy, and then using preg_match_all, instead of preg_match
$s ='[QUOTE="name: Max-Fischer, post: 486662533, member: 123"]I don\'t so much dance as rhythmically convulse.[/QUOTE]';
$s .='[QUOTE="name: Some-Guy, post: 486562533, member: 1234"]Quidquid latine dictum sit, altum videtur[/QUOTE]';
$r = '/\[QUOTE="(.*?)"\](.*?)\[\/QUOTE\]/';
// ^ <--- added to make it less greedy
$m = array();
$arr = array();
preg_match_all($r, $s, $m, PREG_SET_ORDER);
// m[0] = the first quote
// m[1] = the second quote
// m[0][0] = the initial string
// m[0][1] = the string of attributes
// m[0][2] = the quote itself
// element for each quote found in the string
foreach($m as $match) { // since there is more than quote, we loop and operate on them individually
$quote = array();
foreach(explode(',', $match[1]) as $valuepair) { // split the attributes on the comma
preg_match('/\s*(.*): (.*)/', $valuepair, $mm);
// mm[0] = the attribute pairing
// mm[1] = the attribute name
// mm[2] = the attribute value
$quote[$mm[1]] = $mm[2];
}
$arr[] = $quote; // we now build a parent array, to hold each individual quote
}
print_r($arr);
This gives output like:
Array
(
[0] => Array
(
[name] => Max-Fischer
[post] => 486662533
[member] => 123
)
[1] => Array
(
[name] => Some-Guy
[post] => 486562533
[member] => 1234
)
)
I managed to resolve yout problem: to get an associative array. I hope it will help you.
Here is code
$str = <<< PP
[QUOTE=" name : Max-Fischer,post : 486662533,member : 123 "]I don't so much dance as rhythmically convulse.[/QUOTE]
PP;
preg_match_all('/^\[QUOTE=\"(.*?)\"\](?:.*?)]$/', $str, $matches);
preg_match_all('/([a-zA-Z0-9]+)\s+:\s+([a-zA-Z0-9]+)/', $matches[1][0], $result);
$your_data = array_combine($result[1],$result[2]);
echo "<pre>";
print_r($your_data);

PHP: How to use Regular Expression in PHP to Split String in 2

How would I use regular expression with PHP to split the following string into 2 pars as depicted below:
String to be split: 4x330ml
Split into 4x330 and ml
I have tried the following but it does not return the accurate data:
$pdata = "4x330ml"
$data = preg_split('#(?<=\d)(?=[a-z])#i', $pdata);
Then I get something like 4 in $data[0] and x330 in $data[1]
EDIT: Please note that ml could also be cm, kg, etc. A little complicated, which I don't seem to find a solution.
EDIT: Also I have tried the following regex (which I prefer to use at this point) with incomplete results:
$pdata = "5x500ml";
$data = preg_split('/(\d+\.?\d+)|(\w+)i/', $pdata);
This returns:
Array
(
[0] => 5x
[1] => ml
)
500 from that string is not being returned...
Thanks,
You said it could be ml, cm, or kg. and that you don't have to use regex. So, assuming it is always 2 characters at the end, a very simple way to do this would be:
$string = "4x330ml";
$part1 = substr($string, 0, -2); //returns 4x330
$part2 = substr($string, -2, 2); //returns "ml"
This ought to give you what you want.
$pdata = "4x330cm";
$data = preg_match('/([^(ml|cm|kg)]*)(ml|cm|kg)/', $pdata, $group);
echo $group[0].' ';
echo $group[1].' ';
echo $group[2].' ';
Use the preg_match function, and store the results into an array. The 0 index will return the entire matched string. The $group[1] will return just "4x330". The $group[2]$ will return just the "cm".
I'd use preg_match:
$pdata = "4x330ml";
preg_match('/(\d+x\d+)(.*)/',$pdata, $m);
print_r($m);
Output:
Array
(
[0] => 4x330ml
[1] => 4x330
[2] => ml
)
Assuming the units will always be 2 characters long you can use this
$pdata = "4x330ml";
$strNumber = substr($pdata, 0, strlen($pdata)-2);
$strUnit = substr($pdata, strlen($pdata)-2,2);
echo $strNumber; //returns 4x330
echo $strUnit; //returns ml
you can do this without a regex
$string = '4x330ml';
$splitPoint = strrpos($string,'m');
$firstPart = substr($string,0,$string); //gets 4x330
$secondPart = substr($string,$splitPoint); //gets ml
I was able to solve this problem by using the following code:
$data = "4x500ml";
$pdata = preg_split('/(\d+x\d+)/', $data, NULL, PREG_SPLIT_DELIM_CAPTURE);
Which now prints:
array(
[0] =>
[1] => 4x500
[2] => ml
)
It looks like it is capturing the delimeter as array[1] and since the delimeter is actually the first section of the string I want to split, it is fine for now, until I find a better solution.
Thank you all for trying.

Categories