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
Related
I have a string that looks something like this:
abc-def-ghi-jkl-mno-pqr-stu-vwx-yz I'd like to get the content BEFORE the 4th dash, so effectively, I'd like to get abc-def-ghi-jkl assigned to a new string, then I'd like to get mno assigned to a different string.
How could I go about doing this? I tried using explode but that changed it to an array and I didn't want to do it that way.
Try this:
$n = 4; //nth dash
$str = 'abc-def-ghi-jkl-mno-pqr-stu-vwx-yz';
$pieces = explode('-', $str);
$part1 = implode('-', array_slice($pieces, 0, $n));
$part2 = $pieces[$n];
echo $part1; //abc-def-ghi-jkl
echo $part2; //mno
See demo
http://php.net/manual/en/function.array-slice.php
http://php.net/manual/en/function.explode.php
http://php.net/manual/en/function.implode.php
Can you add your source code? I done this one before but I cant remember the exact source code I used. But I am pretty sure I used explode and you can't avoid using array.
EDIT: Mark M answer is right.
you could try using substr as another possible solution
http://php.net/manual/en/function.substr.php
If I see where you are trying to get with this you could also go onto substr_replace
I guess an alternative to explode would be to find the position of the 4th - in the string and then get a substring from the start of the string up to that character.
You can find the position using a loop with the method explained at find the second occurrence of a char in a string php and then use substr(string,0,pos) to get the substring.
$string = "abc-def-ghi-jkl-mno-pqr-stu-vwx-yz";
$pos = -1;
for($i=0;$i<4;$i++)
$pos = strpos($string, '-', $pos+1);
echo substr($string, 0, $pos);
Code isn't tested but the process is easy to understand. You start at the first character (0), find a - and on the next loop you start at that position +1. The loop repeats it for a set number of times and then you get the substring from the start to that last - you found.
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
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);
I have strings like:
t_est1_1
test213_4
tes_tsdfsdf_9
The common part of every string is the LAST underscore _ character.
I need to get the string before this character.
t_est1_12 --> test1
test213_4 --> test213
tes_tsdfsdf_9343 --> testsdfsdf
How can i achieve this in PHP?
Using the basic string functions strpos and substr.
http://fr.php.net/manual/fr/function.explode.php
$a = "abcdef_12345"
$b = array();
// $b[0] = "abcdef";
$b[0] = explode('_',$a,'1');
you can use preg_match function available in php
you need to write regular expression for that...
for example
to get this test1_12 ->> test1
$string='test1_12';
preg_match('((.+?)\_(.*))',$string,$match);
echo $match[1];
What you want is a simple explode, array_slice and implode, also using explode and end, you can get the "id" that is the common part too:
$description = implode('', array_slice(explode('_', $data), 0, -1));
$id = end(explode('_', $data));
As many _ you will have, you'll still be able to expode on them and retrieve the last item containing your id and the first items (0 to -1) will contain your description...
I have some testcases/strings in this format:
o201_01_01a_Testing_to_see_If_this_testcases_passes:without_data
o201_01_01b_Testing_to_see_If_this_testcases_passes:data
rx01_01_03d_Testing_the_reconfiguration/Retest:
Actually this testcase name consists of the actual name and the description.
So, I want to split them like this :
o201_01_01a Testing_to_see_If_this_testcases_passes:without_data
o201_01_01b Testing_to_see_If_this_testcases_passes:data
rx01_01_03d Testing_the_reconfiguration/Retest:
I am unable to figure out the exact way to do this in explode in php
Can anyone help please?
Thanks.
If the first part has always the same length, why don't you use substr, e.g.
$string = "o201_01_01a_Testing_to_see_If_this_testcases_passes:without_data";
$first_part = substr($string, 0, 11); // o201_01_01a
$second_part = substr($string, 12); // Testing_to_see_If_this_testcases_passes:without_data
$results = preg_split("/([a-z0-9]+_[0-9]+_[0-9]+[a-z])(.*)/", $input);
That should give you an array of results, provided I got the regular expression correct.
http://www.php.net/manual/en/function.preg-split.php
Looking at the pattern, it appears that you need to use regular expressions. If this is how they all are, you can cut off the beginning by looking for an upper case character. The code might look like this:
$matches = array()
preg_match('/^[^A-Z]*?/', $string, $matches);
$matches = substr($matches[0], 0, count($matches[0])-1);
Would put the first little part into $matches. Working on second part...