I need to split data from a single word string like below,
$string = "RC9999999999A202";
//Need to split as follows:
$code = "RC"; //This value must be of 2 alphabetic characters
$phone = "9999999999"; //This value must be of 10 digits
$amount = "202"; //This value can be of any length (numeric only)
I tried nothing because I don't have any idea regarding this since I'm a newbie.
Please help!
Please do not leave negative rating, instead try to help me.
If your string will always be like you described 2 chars then 10 digits followed by any number of chars then you can get what you want simply using substr like so :
$string = "RC9999999999A202";
echo $code = substr($string, 0, 2); // get first 2 chars
echo $phone = substr($string, 2, 10); // get 10 chars starting from 3d char
echo $amount = substr($string, 12); // get whatever chars left
Note: this method does not validate any data, it just extract what you have in your string based on what you described in the question.
This will match according to your specifications and populate the variables code, phone and amount.
$string = "RC9999999999A202";
Preg_match("/([A-Z]{2})(\d{10})A(\d+)/", $string, $match);
List($string, $code, $phone, $amount) = $match;
https://3v4l.org/QXVRA
This pattern assumes the "A" is always an "A".
You didn't mention it at all in the question so I assume it's always an "A".
You can use this regex for preg_match:
$str = 'RC9999999999A202';
if (preg_match('/([A-Z]{2})(\d{10})\D*(\d*)/', $str, $m)) {
unset($m[0]); // delete full match from array
print_r($m);
}
Output:
Array
(
[1] => RC
[2] => 9999999999
[3] => 202
)
RegEx Demo
Related
I'm trying with so many examples online to get the numbers between a _ and .. It simple outputs empty string for whatever reason.
String:
/chat_3.txt
I want to be able to extract the number in it, which is 3 in the above string.How do I do that?
I tried as below, but it gives empty output:
$s = '/chat_3.txt';
$matches = array();
$t = preg_match('/_(.*?)\./s', $s, $matches);
Then, I write the output into a file in Joomla like this:
$file = __DIR__ . '/file.txt';
JFile::write($file, $matches[1]);
EDIT:
In fact, I passed array instead of string.
So, the real issue is that
I passed array instead of string
If you need to extract the digits from the last occurrence of .+digits+., you can easily achieve that with a preg_filter function:
$s = array('/chat_3.txt', '/chat_old.txt', '/chat_15.txt');
$matches = array();
$t = preg_filter('/.*_(\d+)\..*/s', '$1',$s);
print_r($t);
See the PHP demo
The preg_filter will return only those values where it found a match. The replaced values will be returned. So, .*_(\d+)\..* will match any 0+ chars as many as possible up to the last _ + 1 or more digits (captured into Group 1) + . + any zero or more chars up to the end of string, and will replace all this with the digits found in Group 1.
I would like to get the second number present in a string.
Maybe you have better ideas than mine.
From this example:
1 PLN = 0.07 Gold
I would like to get only "0.07" from that string.
I obtain it from web scraping so it returns me as a string.
The problem that I have is the following.
The "second number in string" might be with ".", without it, might be composed by only one number ex. "1", or by two "12", might have decimals ex. "1.2", even position may change, because for some currency I will have "1 PLN", "1 USD" for others I will have "1 TW".
So I can't work on position, I can't extract only numbers (I have the "1" at the beginning of the string), I can't extract only INT cause I could have also decimals...
So the only constant of that string - I think (but if you have better ideas pls suggest me) - is that I need the second number I find in the string.
How could I get it?
Sorry If I wasn't enough clear.
Try this:
<?php
$string = '1 PLN = 0.07 Gold';
$pattern = '/\d+\.\d+/';
$matches = array();
$r = preg_match($pattern, $string, $matches);
var_dump($matches); //$matches is array with results
Output:
array(1) {
[0]=>
string(4) "0.07"
}
If its always in this format 1 PLN = 0.07 Gold You can just
$array = explode(" ", $string) with a Space and then get the required number with
$number = $array[3]
Try it out, let me know if it works
You can use a simple regex patter to isolate all numbers, including decimals if any after the equals sign.
The below works if the string will have the same structure, meaning an = a space and then the number that you are after.
= - matches the equals sign
\s - matches the space character immediately after
(\d*\.?\d*) - matches any number of digits followed by an optional period . and then any number of digits
$str = '1 PLN = 0.07 Gold';
preg_match('#=\s(\d*\.?\d*)#',$str,$matches);
print $matches[1];
Will output
0.07
This works regardless of what you have before the = sign.
Say we have string like:
$string = 'ADJKANKNAKLNKALNFKLANFKLNAKLFNKALN';
Say we need to declare a variable containing the first 5 characters (ADJKA) from $string and remove the first 5 characters from original string.
$first = 'ADJKA';
$string = 'NKNAKLNKALNFKLANFKLNAKLFNKALN';
Is there any function in PHP which can achieve this without using second function? I am thinking something similar to the behavior of array_splice(), but with an input string instead of an input array.
(I know that str_splice() isn't a native php function.)
Simply:
$string = substr_replace($string, '', 0, 5);
I was bored:
list($five, $string) = preg_split('/(^.{5})/', $string, null,
PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
In non-buggy versions of php, you can "catch-n-release" the first five characters with \K and limit the splits to a 2-element maximum.
Code: (Demo)
$string = 'ADJKANKNAKLNKALNFKLANFKLNAKLFNKALN';
[$first5, $string] = preg_split('~.{5}\K~', $string, 2);
var_export([$first5, $string]);
Or you can avoid the \K bugs and use a lookbehind.
preg_split('~(?<=.{5})~', $string, 2)
Output:
array (
0 => 'ADJKA',
1 => 'NKNAKLNKALNFKLANFKLNAKLFNKALN',
)
Using PHP I have an array that return this data for an image:
Array
(
[0] => http://website.dev/2014/05/my-file-name-here-710x557.png
[1] => 710
[2] => 557
[3] => 1
)
Based on the demo data above, I need to somehow turn this image URL into:
http://website.dev/2014/05/my-file-name-here.png removing the -710x557 from the string.
Some things to keep in mind are:
The file extension can change and be any type of file type
710x557 might not ALWAYS be a 3 digit x 3 digit number. It could be 2 or 4
The reason I mention this is to show I cannot simply use PHP's string functions to remove the last 12 characters in the string and then add the file extension back because the last string characters could possibly be between 10 and 14 characters long sometimes and not always 12.
I was hoping to avoid a heavy regular expression code but if that is the only or best way here then I say go with it.
How do I write a regex that removes the end of a string that could have a varying length in PHP?
You can use a regex like this:
-\d+x\d+(\.\w+)$
Working demo
The code you can use is:
$re = "/-\\d+x\\d+(\\.\\w+)$/";
$str = "http://website.dev/2014/05/my-file-name-here-710x557.png";
$subst = '\1';
$result = preg_replace($re, $subst, $str, 1);
The idea is to match the resolution -NumbersXNumbers using -\d+x\d+ (that we'll get rid of it) and then capture the file extension by using (\.\w+)$ using capturing group. Check the substitution section above.
As long as it is 2 sets of digits with an 'x' in the middle preceded by a dash you can use this regex:
-[\d]*x[\d]*
$string = 'http://website.dev/2014/05/my-file-name-here-710x557.png';
$pattern = '/-[\d]*x[\d]*/';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
http://phpfiddle.org/lite/code/eh40-6d1x
You can probably use strrpos in the following manner to do this:
$str = substr($str, 0, strrpos($str, '-')) . substr($str, strrpos($str, '.'));
You can use this regex based code:
$str = "http://website.dev/2014/05/my-file-name-here-710x557.png";
$re = '/-([^-]+)(?=\.[^-]*$)/';
$result = preg_replace($re, '', $str, 1);
//=> http://website.dev/2014/05/my-file-name-here.png
RegEx Demo
$newsrc = preg_replace('#\-\d+x\d+(\.\w+$)#', '$1', $arr[0]);
see http://ideone.com/ZsELQ0
i have string like
cream 100G
sup 5mg Children
i want to split it before the first occurrence of a digit. so the result should be
array(
array('cream','100G'),
array('sup','5mg Children')
);
can so one tell me how to create pattern for this ?
i tried
list($before, $after) = array_filter(array_map('trim',
preg_split('/\b(\d+)\b/', $t->formula)), 'strlen');
but something went wrong.
Try this:
<?php
$first_string = "abc2 2mg";
print_r( preg_split('/(?=\d)/', $first_string, 2));
?>
Will output:
Array ( [0] => abc [1] => 2 2mg )
The regular expression solution would be to call preg_split as
preg_split('/(?=\d)/', $t->formula, 2)
The main point here is that you do not consume the digit used as the split delimiter by using positive lookahead instead of capturing it (so that it remains in $after) and that we ensure the split produces no more than two pieces by using the third argument.
You don't need regular expressions for that:
$str = 'cream 100g';
$p = strcspn($str, '0123456789');
$before = substr($str, 0, $p);
$after = substr($str, $p);
echo "before: $before, after: $after";
See also: strcspn()
Returns the length of the initial segment of $str which does not contain any of the characters in '0123456789', aka digits.