PHP: best method to trim a substring from a string - php

Want to process a set of strings, and trim some ending "myEnding" from the end of each string if it exists.
What is the simplest way to do it?
I know that everything is possible with regexp, but thus seems to be a simple task, and I wonder whether a simpler tool for this exists.
Thanks
Gidi

ima go with preg_replace on this one.
$output = preg_replace('/myEnding$/s', '', $input);

Try this:
$s = "foobarmyEnding";
$toRemove = "myEnding";
$len = strlen($toRemove);
if (strcmp(substr($s, -$len, $len), $toRemove) === 0)
{
$s = substr($s, 0, -$len);
}
ideone

rtrim http://php.net/manual/en/function.rtrim.php
$str = "foobarmyEnding";
$str = rtrim($str, 'myEnding');
// str == "foobar"
ltrim is the same deal for the start of a string http://php.net/manual/en/function.ltrim.php
You could also use str_replace to replace a search term with with an empty string but its slower then rtrim/ltrim if you need to amend the start or end of a string

Related

str replace - replace the x-value

Assuming I have a string
$str="0000,1023,1024,1025,1024,1023,1027,1025,1024,1025,0000";
there are three 1024, I want to replace the third with JJJJ, like this :
output :
0000,1023,1024,1025,1024,1023,1027,1025,JJJJ,1025,0000
how to make str_replace can do it
thanks for the help
As your question asks, you want to use str_replace to do this. It's probably not the best option, but here's what you do using that function. Assuming you have no other instances of "JJJJ" throughout the string, you could do this:
$str = "0000,1023,1024,1025,1024,1023,1027,1025,1024,1025,0000";
$str = str_replace('1024','JJJJ',$str,3)
$str = str_replace('JJJJ','1024',$str,2);
Here is what I would do and it should work regardless of values in $str:
function replace_str($str,$search,$replace,$num) {
$pieces = explode(',',$str);
$counter = 0;
foreach($pieces as $key=>$val) {
if($val == $search) {
$counter++;
if($counter == $num) {
$pieces[$key] = $replace;
}
}
}
return implode(',',$pieces);
}
$str="0000,1023,1024,1025,1024,1023,1027,1025,1024,1025,0000";
echo replace_str($str, '1024', 'JJJJ', 3);
I think this is what you are asking in your comment:
function replace_element($str,$search,$replace,$num) {
$num = $num - 1;
$pieces = explode(',',$str);
if($pieces[$num] == $search) {
$pieces[$num] = $replace;
}
return implode(',',$pieces);
}
$str="0000,1023,1024,1025,1024,1023,1027,1025,1024,1025,0000";
echo replace_element($str,'1024','JJJJ',9);
strpos has an offset, detailed here: http://php.net/manual/en/function.strrpos.php
So you want to do the following:
1) strpos with 1024, keep the offset
2) strpos with 1024 starting at offset+1, keep newoffset
3) strpos with 1024 starting at newoffset+1, keep thirdoffset
4) finally, we can use substr to do the replacement - get the string leading up to the third instance of 1024, concatenate it to what you want to replace it with, then get the substr of the rest of the string afterwards and concatenate it to that. http://www.php.net/manual/en/function.substr.php
You can either use strpos() three times to get the position of the third 1024 in your string and then replace it, or you could write a regex to use with preg_replace() that matches the third 1024.
if you want to find the last occurence of your string you can used strrpos
Do it like this:
$newstring = substr_replace($str,'JJJJ', strrpos($str, '1024'), strlen('1024') );
See working demo
Here's a solution with less calls to one and the same function and without having to explode, iterate over the array and implode again.
// replace the first three occurrences
$replaced = str_replace('1024', 'JJJJ', $str, 3);
// now replace the firs two, which you wanted to keep
$final = str_replace('JJJJ', '1024', $replaced, 2);

PHP - Strip a specific string out of a string

I've got this string, but I need to remove specific things out of it...
Original String: hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64.
The string I need: sh-290-92.ch-215-84.lg-280-64.
I need to remove hr-165-34. and hd-180-1.
!
EDIT: Ahh ive hit a snag!
the string always changes, so the bits i need to remove like "hr-165-34." always change, it will always be "hr-SOMETHING-SOMETHING."
So the methods im using wont work!
Thanks
Depends on why you want to remove exactly those Substrigs...
If you always want to remove exactly those substrings, you can use str_replace
If you always want to remove the characters at the same position, you can use substr
If you always want to remove substrings between two dots, that match certain criteria, you can use preg_replace
$str = 'hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64';
$new_str = str_replace(array('hr-165-34.', 'hd-180-1.'), '', $str);
Info on str_replace.
The easiest and quickest way of doing this is to use str_replace
$ostr = "hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64";
$nstr = str_replace("hr-165-34.","",$ostr);
$nstr = str_replace("hd-180-1.","",$nstr);
<?php
$string = 'hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64';
// define all strings to delete is easier by using an array
$delete_substrings = array('hr-165-34.', 'hd-180-1.');
$string = str_replace($delete_substrings, '', $string);
assert('$string == "sh-290-92.ch-215-84.lg-280-64" /* Expected result: string = "sh-290-92.ch-215-84.lg-280-64" */');
?>
Ive figured it out!
$figure = $q['figure']; // hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64
$s = $figure;
$matches = array();
$t = preg_match('/hr(.*?)\./s', $s, $matches);
$s = $figure;
$matches2 = array();
$t = preg_match('/hd(.*?)\./s', $s, $matches2);
$s = $figure;
$matches3 = array();
$t = preg_match('/ea(.*?)\./s', $s, $matches3);
$str = $figure;
$new_str = str_replace(array($matches[0], $matches2[0], $matches3[0]), '', $str);
echo($new_str);
Thanks guys!

Help on parsing formatted string

I have strings:
17s 283ms
48s 968ms
The string values are never the same and I want to extract the "second" value from it. In this case, the 17 and the 48.
I'm not very good with regex, so the workaround I did was this:
$str = "17s 283ms";
$split_str = explode(' ', $str);
foreach($split_str as $val){
if(strpos($val, 's') !== false) $sec = intval($val);
}
The problem is, the character 's' exists in both split_str[0] and split_str[1], so my $sec variable keeps obtaining 283, instead of 17.
Again, I'm not very good with regex, and I'm pretty sure regex is the way to go in this case. Please assist. Thanks.
You don't even need to use regex for this.
$seconds = substr($str, 0, strspn($str, '1234567890'));
The above solution will extract all the digits from the beginning of the string. Doesn't matter if the first non-digit character is "s", a space, or anything else.
But why bother?
You can even just cast $str to an int:
$seconds = (int)$str; // equivalent: intval($str)
See it in action.
Regular expressions are definite overkill for such a simple task. Don't use dynamite to drill holes in the wall.
You could do this like so:
preg_match('/(?<seconds>\d+)s\s*(?<milliseconds>\d+)ms/', $var, $matches);
print_r($matches);
If the string will always be formatted in this manner, you could simply use:
<?php
$timeString = '17s 283ms';
$seconds = substr($timeString, 0, strpos($timeString, 's'));
?>
Well, i guess that you can assume seconds always comes before milliseconds. No need for regexp if the format is consistent. This should do it:
$parts = explode(' ', $str);
$seconds = rtrim($parts[0], 's')
echo $seconds; // 17s
This will split the string by space and take the first part 17s. rtrim is then used to remove 's' and you're left with 17.
(\d+s) \d+ms
is the right regexp. Usage would be something like this:
$str = "17s 283ms";
$groups = array();
preg_match("/(\d+)s \d+ms/", $str, $groups);
Then, your number before ms would be $groups[1].

Increment integer at end of string

I have a string, "Chicago-Illinos1" and I want to add one to the end of it, so it would be "Chicago-Illinos2".
Note: it could also be Chicago-Illinos10 and I want it to go to Chicago-Illinos11 so I can't do substr.
Any suggested solutions?
Complex solutions for a really simple problem...
$str = 'Chicago-Illinos1';
echo $str++; //Chicago-Illinos2
If the string ends with a number, it will increment the number (eg: 'abc123'++ = 'abc124').
If the string ends with a letter, the letter will be incremeted (eg: '123abc'++ = '123abd')
Try this
preg_match("/(.*?)(\d+)$/","Chicago-Illinos1",$matches);
$newstring = $matches[1].($matches[2]+1);
(can't try it now but it should work)
$string = 'Chicago-Illinois1';
preg_match('/^([^\d]+)([\d]*?)$/', $string, $match);
$string = $match[1];
$number = $match[2] + 1;
$string .= $number;
Tested, works.
explode could do the job aswell
<?php
$str="Chicago-Illinos1"; //our original string
$temp=explode("Chicago-Illinos",$str); //making an array of it
$str="Chicago-Illinos".($temp[1]+1); //the text and the number+1
?>
I would use a regular expression to get the number at the end of a string (for Java it would be [0-9]+$), increase it (int number = Integer.parse(yourNumberAsString) + 1), and concatenate with Chicago-Illinos (the rest not matched by the regular expression used for finding the number).
You can use preg_match to accomplish this:
$name = 'Chicago-Illinos10';
preg_match('/(.*?)(\d+)$/', $name, $match);
$base = $match[1];
$num = $match[2]+1;
print $base.$num;
The following will output:
Chicago-Illinos11
However, if it's possible, I'd suggest placing another delimiting character between the text and number. For example, if you placed a pipe, you could simply do an explode and grab the second part of the array. It would be much simpler.
$name = 'Chicago-Illinos|1';
$parts = explode('|', $name);
print $parts[0].($parts[1]+1);
If string length is a concern (thus the misspelling of Illinois), you could switch to the state abbreviations. (i.e. Chicago-IL|1)
$str = 'Chicago-Illinos1';
echo ++$str;
http://php.net/manual/en/language.operators.increment.php

Get the string after a string from a string

what's the fastest way to get only the important_stuff part from a string like this:
bla-bla_delimiter_important_stuff
_delimiter_ is always there, but the rest of the string can change.
here:
$arr = explode('delimeter', $initialString);
$important = $arr[1];
$result = end(explode('_delimiter_', 'bla-bla_delimiter_important_stuff'));
I like this method:
$str="bla-bla_delimiter_important_stuff";
$del="_delimiter_";
$pos=strpos($str, $del);
cutting from end of the delimiter to end of string
$important=substr($str, $pos+strlen($del)-1, strlen($str)-1);
note:
1) for substr the string start at '0' whereas for strpos & strlen takes the size of the string (starts at '1')
2) using 1 character delimiter maybe a good idea
$importantStuff = array_pop(explode('_delimiter_', $string));
$string = "bla-bla_delimiter_important_stuff";
list($junk,$important_stufF) = explode("_delimiter_",$string);
echo $important_stuff;
> important_stuff

Categories