PHP preg_replace number to two parts - php

I need to split number with length 5 (example "11111") into two parts with space like "111 11".
What am I missing in my code?
$zip = "11111";
$res = preg_replace('/^\d{3}[ ]?\d{2}/', '$0 $2', $zip);
echo $zip; // returns 11111
echo $res; // returns 11111
Thank you very much
Thanks to all, I missed simple brackets ()
I need to use this to little bit difficult methods :)

Do you really need a regex for this? If it is always a five digit number it's easy to break it apart and reconstruct it as necessary..
echo sprintf("%s %s", substr($zip, 0, 3), substr($zip, -2));
See it in action

John Conde’s answer is great, but since your question is:
What am I missing in my code?
my answer is that you have to capture the groups with parentheses:
$zip = "11111";
$res = preg_replace('/^(\d{3})[ ]?(\d{2})/', '$1 $2', $zip);
echo $zip;
echo PHP_EOL;
echo $res;

Why use a regex for something so simple?
$zip = '11111';
$first_part = substr($zip, 0, 3);
$last_part = substr($zip, 3);
As for your regex, you're not using capture groups ((...)), so $0/$2 will never get defined.

Related

Extract exact letters from a string

Lets say I have this string:
CNVFJD-0905-05-BX
CNV will always be there , same with the first '-'.
What I need is to 'extract' whats between CNV and the first line(in this example I would need 'FJD'.
I don't really know how to approach this.
Thank you.
You can use substr, try this
substr($sring, 3, strpos($string, '-'));
With sscanf:
$str = "CNVFJD-0905-05-BX";
sscanf($str, "CNV%[A-Z]-", $result);
echo $result;
$parts = explode("-", $string);
$result = substr($parts[0], 3);
See here for working example https://3v4l.org/pRJ3e

PHP: preg_replace() to get "parent" component of NameSpace

How can I use the preg_replace() replace function to only return the parent "component" of a PHP NameSpace?
Basically:
Input: \Base\Ent\User; Desired Output: Ent
I've been doing this using substr() but I want to convert it to regex.
Note: Can this be done without preg_match_all()?
Right now, I also have a code to get all parent components:
$s = '\\Base\\Ent\\User';
print preg_replace('~\\\\[^\\\\]*$~', '', $s);
//=> \Base\Ent
But I only want to return Ent.
Thank you!
As Rocket Hazmat says, explode is almost certainly going to be better here than a regex. I would be surprised if it's actually slower than a regex.
But, since you asked, here's a regex solution:
$path = '\Base\Ent\User';
$search = preg_match('~([^\\\\]+)\\\\[^\\\\]+$~', $path, $matches);
if($search) {
$parent = $matches[1];
}
else {
$parent = ''; // handles the case where the path is just, e.g., "User"
}
echo $parent; // echos Ent
I think maybe preg_match might be a better choice for this.
$s = '\\Base\\Ent\\User';
$m = [];
print preg_match('/([^\\\\]*)\\\\[^\\\\]*$/', $s, $m);
print $m[1];
If you read the regular expression backwards, from the $, it says to match many things that aren't backslashes, then a backslash, then many things that aren't backslashes, and save that match for later (in $m).
How about
$path = '\Base\Ent\User';
$section = substr(strrchr(substr(strrchr($path, "\\"), 1), "\\"), 1);
Or
$path = '\Base\Ent\User';
$section = strstr(substr($path, strpos($path, "\\", 1)), "\\", true);

Php split a string to to string

I want to split a variable that I call for $ NowPlaying which contains the results of the current song. I would now like to share the following - so I get two new variables containing $ artist $ title. Having searched and tried to find a solution, but have stalled grateful for a little assistance, and help
<?php
// Assuming $NowPlaying is something like "J. Cole - Chaining Day"
// $array = explode("-", $NowPlaying); //enter a delimiter here, - is the example
$array = explode(" - ", $NowPlaying); //DJHell pointed out this is better
$artist = $array[0]; // J. Cole
$song = $array[1]; // Chaining Day
// Problems will arise if the delimiter is simply (-), if it is used in either
// the song or artist name.. ie ("Jay-Z - 99 Problems") so I advise against
// using - as the delimiter. You may be better off with :.: or some other string
?>
Sounds like you're wanting to use explode()
http://php.net/manual/en/function.explode.php
Use php explode() function
$str_array = explode(' - ', $you_song);
// then you can get the variables you want from the array
$artist = $str_array[index_of_artist_in_array];
$title = $str_array[index_of_title_in_array];
I would usually do some thing like this:
<?php
$input = 'Your - String';
$separator = ' - ';
$first_part = substr($input, 0, strpos($input, $separator));
$second_part = substr($input, (strpos($input, $separator) + strlen($separator)), strlen($input));
?>
I have looked at a couple split string questions and no one suggests using the php string functions. Is there a reason for this?
list() is made for exactly this purpose.
<?php
list($artist, $title) = explode(' - ', $NowPlaying);
?>
http://php.net/manual/en/function.list.php

PHP read everything until first comma

I have string that will look like this:
$string = "hello, my, name, is, az";
Now I just wanna echo whatever is there before first comma. I have been using following:
echo strstr($this->tags, ',', true);
and It has been working great, but the problem it only works php 5.3.0 and above. I am currently on PHP 5.2.
I know this could be achieve through regular express by pregmatch but I suck at RE.
Can someone help me with this.
Regards,
<?php
$string = "hello, my, name, is, az";
echo substr($string, 0, strpos($string, ','));
You can (and should) add further checks to avoid substr if there's no , in the string.
Use explode than,
$arr = explode(',', $string,2);
echo $arr[0];
You can explode this string using comma and read first argument of array like this
$string = "hello, my, name, is, az";
$str = explode(",", $string, 2);
echo $str[0];
$parts = explode(',',$string);
echo $parts[0];
You can simple use the explode function:
$string = "hello, my, name, is, az";
$output = explode(",", $string);
echo $output[0];
Too much explosives for a small work.
$str = current(explode(',', $string));

How to convert a string with numbers and spaces into an int

I have a small problem. I am tryng to convert a string like "1 234" to a number:1234
I cant't get there. The string is scraped fro a website. It is possible not to be a space there? Because I've tried methods like str_replace and preg_split for space and nothing. Also (int)$abc takes only the first digit(1).
If anyone has an ideea, I'd be greatefull! Thank you!
This is how I would handle it...
<?php
$string = "Here! is some text, and numbers 12 345, and symbols !£$%^&";
$new_string = preg_replace("/[^0-9]/", "", $string);
echo $new_string // Returns 12345
?>
intval(preg_replace('/[^0-9]/', '', $input))
Scraping websites always requires specific code, you know how you receive the input - and you write code that is required to make it usable.
That is why first answer is still str_replace.
$iInt = (int)str_replace(array(" ", ".", ","), "", $iInt);
$str = "1 234";
$int = intval(str_replace(' ', '', $str)); //1234
I've just came into the same issue, however the answer that was provided wasn't covering all the different cases I had...
So I made this function (the idea popped in my mind thanks to Dan) :
function customCastStringToNumber($stringContainingNumbers, $decimalSeparator = ".", $thousandsSeparator = " "){
$numericValues = $matches = $result = array();
$regExp = null;
$decimalSeparator = preg_quote($decimalSeparator);
$regExp = "/[^0-9$decimalSeparator]/";
preg_match_all("/[0-9]([0-9$thousandsSeparator]*)[0-9]($decimalSeparator)?([0-9]*)/", $stringContainingNumbers, $matches);
if(!empty($matches))
$matches = $matches[0];
foreach($matches as $match):
$numericValues[] = (float)str_replace(",", ".", preg_replace($regExp, "", $match));
endforeach;
$result = $numericValues;
if(count($numericValues) === 1)
$result = $numericValues[0];
return $result;
}
So, basically, this function extracts all the numbers contained inside of a string, no matter how many text there is, identifies the decimal separator and returns every extracted number as a float.
One can specify what decimal separator is used in one's country with the $decimalSeparator parameter.
Use this code for removing any other characters like .,:"'\/, !##$%^&*(), a-z, A-Z :
$string = "This string involves numbers like 12 3435 and 12.356 and other symbols like !## then the output will be just an integer number!";
$output = intval(preg_replace('/[^0-9]/', '', $string));
var_dump($output);

Categories