How can I get number from a special string ? PHP - php

For example, 3 string are the following :
##7##
##563##
##120058##
How can I get those number like this :
echo first number is 7
echo second number is 563
echo third number is 120058
Thank you very much!

$numberAsString = trim($string, '##')
Is probably the easiest and fastest in this case. The output is still a string in this case, but in most cases that doesn't really matter. If it does in your case, you can use (int), (float) or the like to get it to the correct type.
Of course, regex would also be possible, e.g.:
$didMatch = preg_match('/#+([^#]+)#+/', $string, $matches);
Another possibility still is first extract the remaining part after the initial 2 # and then cast to a number, which seems to be always int in this case:
$number = (int)substr($string, 2);
Still another possibility would be to go by the count of the characters and just use substr like:
$numberAsString = substr($string, 2, -2);
Or you could be creative and use something like explode + implode + array functions:
$numberAsString = array_slice(explode('#', implode('', array_slice(explode('#', $string), 2))), 0, -2);
Of course, this last one is purely to show that it can be done in various ways, as it's very inefficient and impractical, but there are surely dozens of other ways.
In case you use this in a tight loop or somewhere where performance really matters, I would benchmark different possibilities - on a guess, I'd say that either the trim or the pure substring solution would be the fastest.

$str = "##563##";
preg_match("|\d+|", $str, $res);
print_r($res);

Just call the filter_var() function it will return the number only.
Whatever the input is, it will only filter the number for you!
filter_var("##120058##", FILTER_SANITIZE_NUMBER_INT) // return 120058
filter_var("*##20kkk", FILTER_SANITIZE_NUMBER_INT) // return 20

Related

Simple way to insert a string into another string - PHP

How can I add string to another string after a specific character in PHP? Strings are coming from Database.
$stringDB= "FZE-17-01";
$string_add="RTL";
Final output= FZE-RTL-17-01
I tried functions but I don't want to use a position based function like substr_replace after 4 characters, etc. Any good alternative. $string_add after first -
One of many variants is to use array_splice
$arr = explode('-', $stringDB);
array_splice($arr, 1,0, $string_add);
echo implode('-', $arr);
Hope this could help you.
$stringDB= "FZE-17-01";
$string_add="RTL";
echo $newstr = substr_replace($stringDB, $string_add, 4, 0);
PHP substr_replace

How to split combined string

I have a string which looks like this:
21/04/2014,16:57:28,19,0,2021/04/2014,16:57:48,19,0,20
I would like to split it so that I get something like the following:
21/04/2014,16:57:28,19,0,20
21/04/2014,16:57:48,19,0,20
I have tried using php's substr which I thought was giving results but it duplicated this '21/04/2014,16:57:48,19,0,20' twice.
$data3 = array(substr($data1, -27), substr($data1, 27));
Even tried a regex with no luck.
If length of parts you want to get is constant you can use str_split function with second parameter.
$data = str_split($string, 27);
Elon Than's answer is the perfect solution if, as he states, the length is constant. However, I just thought I'd add this solution in case (for example) the '19' could also be '3' (or whatever):
preg_match_all("/\d{2}\/\d{2}\/\d{4}\,\d{2}:\d{2}:\d{2},\d{1,2},\d{1},\d{2}/", $string, $matches);
var_dump($matches[0]);
Notice the \d{1,2} will include any number that is 1 or 2 digits.
$data3 = array(substr($data1, 0, 27), substr($data1, 27));

How to split characters with "-" character?

I generated a serial number with php, the length of this serial number is 16 characters, I want to split this serial number in 4 characters with dash(-) character, like this format xxxx-xxxx-xxxx-xxxx so I wrote this php code:
for ($d=0; $d<=3; $d++){
$tmp .= ($tmp ? "-" : null).substr($serial,$d,4);
}
so this loop will return a serial number with xxxx-xxxx-xxxx-xxxx format,
I want to know is there any better way or function in php?
I searched in internet I found sprintf and number_format but I don't know how can I use this function for this format !
I would use str_split() and implode():
$result = implode( '-', str_split( $serial, 4));
str_split() will break the string into an array, where each element has 4 characters. Then, implode() joins those array pieces together with a dash.
So, if we generate a random $serial with:
$serial = substr(md5(uniqid(rand(), true)), 0, 16);
We would get as output something similar to:
59e6-997f-8446-80a2
Try this :
$str = "xxxxxxxxxxxxxxxx";
echo substr(chunk_split($str, 4, '-'), 0, -1);
Output :
xxxx-xxxx-xxxx-xxxx
Ref: http://www.php.net/manual/en/function.chunk-split.php
str_split, fairly clear...
$hyphenated = implode( '-', str_split( $str, 4));
That is pretty clear, but it seems kind of wasteful to generate an array only to implode it. So I wondered if there was another way...
Faster with preg_replace?
I tried a regex, thinking that would eliminate the need for an intermediate array. After all, why have one problem, when you can have two!
$hyphenated = preg_replace('/(.{4})(?=.)/', '$1-', $str);
That little beastie looks for 4 characters, and as long they are followed by at least one more character, will insert a slash after them.
Trouble is, it turned out to be around 25% slower :(
chunk_split faster and with the same great minty taste!
Prasanth Bendra posted a pretty efficient answer which needs no intermediate array
$hyphenated=substr(chunk_split($str, 4, '-'), 0, -1); 
Result! This was at least 25% faster than using str_split measured on a 16 character input string, and just as clear as the str_split method.
You can try str_split() with an implode() such as:
$tmpArray = str_split($tmp, 4);
$serialNumber = implode('-', $tmpArray);

PHP Using str_word_count with strsplit to form array after x words

I've got a large string that I want to put in an array after each 50 words. I thought about using strsplit to cut, but realised that wont take the words in to consideration, just split when it gets to x char.
I've read about str_word_count but can't work out how to put the two together.
What I've got at the moment is:
$outputArr = str_split($output, 250);
foreach($outputArr as $arOut){
echo $arOut;
echo "<br />";
}
But I want to substitute that to form each item of the array at 50 words instead of 250 characters.
Any help will be much appreciated.
Assuming that str_word_count is sufficient for your needs¹, you can simply call it with 1 as the second parameter and then use array_chunk to group the words in groups of 50:
$words = str_word_count($string, 1);
$chunks = array_chunk($words, 50);
You now have an array of arrays; to join every 50 words together and make it an array of strings you can use
foreach ($chunks as &$chunk) { // important: iterate by reference!
$chunk = implode(' ', $chunk);
}
¹ Most probably it is not. If you want to get what most humans consider acceptable results when processing written language you will have to use preg_split with some suitable regular expression instead.
There's another way:
<?php
$someBigString = <<<SAMPLE
This, actually, is a nice' old'er string, as they said, "divided and conquered".
SAMPLE;
// change this to whatever you need to:
$number_of_words = 7;
$arr = preg_split("#([a-z]+[a-z'-]*(?<!['-]))#i",
$someBigString, $number_of_words + 1, PREG_SPLIT_DELIM_CAPTURE);
$res = implode('', array_slice($arr, 0, $number_of_words * 2));
echo $res;
Demo.
I consider preg_split a better tool (than str_word_count) here. Not because the latter is inflexible (it is not: you can define what symbols can make up a word with its third param), but because preg_split will essentially stop processing the string after getting N items.
The trick, as quite common with this function, is to capture delimiters as well, then use them to reconstruct the string with the first N words (where N is given) AND punctuation marks saved.
(of course, the regex used in my example does not strictly comply to str_word_count locale-dependent behavior. But it still restricts the words to consist of alpha, ' and - symbols, with the latter two not at the beginning and the end of any word).

PHP : Get a number between 2 strings

I have this string:
a:3:{i:0;i:2;i:1;i:3;i:2;i:4;}
I want to get number between "a:" and ":{" that is "3".
I try to user substr and strpos but no success.
I'm newbie in regex , write this :
preg_match('/a:(.+?):{/', $v);
But its return me 1.
Thanks for any tips.
preg_match returns the number of matches, in your case 1 match.
To get the matches themselves, use the third parameter:
$matches = array();
preg_match(/'a:(\d+?):{/', $v, $matches);
That said, I think the string looks like a serialized array which you could deserialize with unserialize and then use count on the actual array (i.e. $a = count(unserialize($v));). Be careful with userprovided serialized strings though …
If you know that a: is always at the beginning of the string, the easiest way is:
$array = explode( ':', $string, 3 );
$number = $array[1];
You can use sscanfDocs to obtain the number from the string:
# Input:
$str = 'a:3:{i:0;i:2;i:1;i:3;i:2;i:4;}';
# Code:
sscanf($str, 'a:%d:', $number);
# Output:
echo $number; # 3
This is often more simple than using preg_match when you'd like to obtain a specific value from a string that follows a pattern.
preg_match() returns the number of times it finds a match, that's why. you need to add a third param. $matches in which it will store the matches.
You were not too far away with strpos() and substr()
$pos_start = strpos($str,'a:')+2;
$pos_end = strpos($str,':{')-2;
$result = substr($str,$pos_start,$pos_end);
preg_match only checks for appearance, it doesn't return any string.

Categories