I need only one replacement of a string within a string, but since string that am intend to replace is repeated in the haystack I need to precise start pointer and how many times replacement should be done. I did not found any mention of start offstet if php's string replace functions.
str_replace(substr($string,$start),$replace)
You can use substr, for instance :
$str = "This This This";
echo substr($str, 0, 6) . str_replace('This', 'That', substr($str, 6)); // This This That
You could use some other functions than str_replace that supports a limited search, for example preg_replace:
preg_replace('/'.preg_quote($search, '/').'/', $replacement, $str, 1)
Or a combination of explode and implode:
implode($replacement, explode($search, $str, 2))
Related
I need to know how to do this reliably with the least amount of calls.
I have a string and I need to remove the 8th character from it. It doesn't matter what the char is, I just need to remove ONLY the 8th char.
I came up with this but a little too unwieldy for me.
// 12345678901234567890
$str = '5NMSG3AB1AH353158';
// after removing char, result should be:
// 5NMSG3A1AH353158
$r = str_split($str);
unset($r[7]);
echo join('', $r);
Possibly Regex?
Here are some solutions:
$str = substr($str, 0, 7) . substr($str, 8);
$str = substr_replace($str, '', 7, 1);
$str = preg_replace('/(.{7})./', '$1', $str, 1);
$str = preg_replace('/.{7}\K./', '', $str, 1);
I'd go for substr() or better substr_replace() as this will certainly be fastest and most easy to read.
substr_replace makes this very simple.
$string = substr_replace($string, '', 7, 1);
It can also take an array of strings as its first parameter, and do the same replacement in all of them, which can be pretty handy.
Like this
$str = '5NMSG3AB1AH353158';
echo preg_replace('/^(.{7})./', '\1', $str);
Output:
5NMSG3A1AH353158
Sandbox
Explanation
^ start of string
(...) capture
. match any
{7} seven times
. match any one time
Then the replacement
\1 first capture group
Basically capture the first 7 chars, then match the 8th, and replace that with the captured 7 chars. Which effectively removes the 8th.
UPDATE
here is another way I like (I haven't used that function sense college, I think):
$s = '5NMSG3A1AH353158';
echo substr_replace($s,'',7,1); //strings are 0 based
sandbox
substr_replace() replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.
mixed substr_replace( mixed $string, mixed $replacement, mixed $start [, mixed $length ] )
http://php.net/manual/en/function.substr-replace.php
Simple.
I am running into a problem trying to do a replacement on a few strings. Essentially what I have is a bunch of prices on my page that look like
RMB148.00
What i am trying to do is run a replace on only the last 2 numbers so i can do something like
RMB14800
Preg replace works fine for the RMB part because it is always there.
My problem is the last two numbers can be anything it all depends on the price so I cant just remove and replace, I need to just wrap HTML <sup> tags around them.
$string = $product['price'];
$string = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $string);
echo preg_replace('/RMB/', '<sup class="currency-sym">RMB</sup>', $string, 1);
Assuming the last two characters are digits, you could just
$string=preg_replace('/(\d\d)$/', '<sup class="currency-sym">\1</sup>', $string);
If not,
$string=preg_replace('/(..)$/', '<sup class="currency-sym">\1</sup>', $string);
should do the trick.
Alternativly use
$string=substr($string,0,-2).'<sup class="currency-sym">'.substr($string,-2).'</sup>';
Here is a regex solution that looks for the final digit notation at the end of your string.
$string = 'RMB148.00';
$string = preg_replace('/(\d+)\.(\d{2})\z/','$1<sup>$2</sup>',$string);
echo $string;
You could use the following with the explode () function
$string = explode ('.', $product['price']);
$new_string = $string[0].'<sup>'. $string [1]. '</sup>';
And do the regex for the RMB the same way.
Code.
<?php
$string = '14842.00';
$string = substr($string, 0, strlen($string) - 2) . '<sup>' . substr($string, strlen($string) - 2, 2) . '</sup>';
echo $string;
Try online sandbox.
Explanation.
substr($s, $i, $l) gets $l symbols of $s, started from $i index (indexes starts from zero).
So first substr($string, 0, strlen($string) - 2) gets all string except last two symbols.
Second substr($string, strlen($string) - 2, 2) gets only last two symbols.
More about substr.
You should use a pattern matching regex. Note the $1 in the replacement argument matches (\d{2}) in the pattern argument. preg_replace() only replaces the matched pattern. This pattern matches . followed by any two digits. Since . is not included in the replacement argument it does not show up in your $string.
$string = preg_replace('/\.(\d{2})$/', '<sup>$1</sup>', $string);
Of course, you could use one preg_replace to do what you want:
$string = preg_replace('/^(RMB)(\d+)(\.(\d{2}))?$/', "<sup class='currency-sym'>$1</sup>$2<sup>$4</sup>", $string);
The second example may be a good idea if you want DOM integrity, otherwise it creates an empty <sup></sup> when there is no decimal.
I would like to know how I can cut a string in PHP starting from the last character -> to a specific character. Lets say I have following link:
www.whatever.com/url/otherurl/2535834
and I want to get 2535834
Important note: the number can have a different length, which is why I want to cut out to the / no matter how many numbers there are.
Thanks
In this special case, an url, use basename() :
echo basename('www.whatever.com/url/otherurl/2535834');
A more general solution would be preg_replace(), like this:
<----- the delimiter which separates the search string from the remaining part of the string
echo preg_replace('#.*/#', '', $url);
The pattern '#.*/#' makes usage of the default greediness of the PCRE regex engine - meaning it will match as many chars as possible and will therefore consume /abc/123/xyz/ instead of just /abc/ when matching the pattern.
Use
explode() AND end()
<?php
$str = 'www.whatever.com/url/otherurl/2535834';
$tmp = explode('/', $str);
echo end ($tmp);
?>
Working Demo
This should work for you:
(So you can get the number with or without a slash, if you need that)
<?php
$url = "www.whatever.com/url/otherurl/2535834";
preg_match("/\/(\d+)$/",$url,$matches);
print_r($matches);
?>
Output:
Array ( [0] => /2535834 [1] => 2535834 )
With strstr() and str_replace() in action
$str = 'www.whatever.com/url/otherurl/2535834';
echo str_replace("otherurl/", "", strstr($str, "otherurl/"));
strstr() finds everything (including the needle) after the needle and the needle gets replaced by "" using str_replace()
if your pattern is fixed you can always do:
$str = 'www.whatever.com/url/otherurl/2535834';
$tmp = explode('/', $str);
echo $temp[3];
Here's mine version:
$string = "www.whatever.com/url/otherurl/2535834";
echo substr($string, strrpos($string, "/") + 1, strlen($string));
I've got a string which goes something like myString__sfsdfsf
All I know is that there is a __ somewhere in the string. Content of the string and number of characters is unknown.
I want to remove the __ and all characters that follow so I am left with just myString. How can I achieve this using PHP?
This can be done in several ways. PHP has lots of string functions. You can pick one depending on your requirements. Here are some ways:
Use substr() and strpos():
$str = 'myString__sfsdfsf';
echo substr($str, 0, strpos($str, '__')); // => myString
Or use strtok():
echo strtok($str, '__'); // => myString
Or, maybe even explode():
echo explode('__', $str)[0]; // => myString
You can make use of strpos() and substr():
$str = 'myString__sfsdfsf';
echo substr($str, 0, strpos($str, '__'));
This should be quite fast. However if you need something more fancy than that, you probably want to look into regular expressions, e.g. preg_match().
Use list() and explode():
list($string,) = explode('_', 'myString__sfsdfsf');
echo $string; // Outputs: myString
A str_replace() would also work
$string = str_replace('__', '', $string);
Ignore that, didn't read your question properly
I need to know how I can replace the last "s" from a string with ""
Let's say I have a string like testers and the output should be tester.
It should just replace the last "s" and not every "s" in a string
how can I do that in PHP?
if (substr($str, -1) == 's')
{
$str = substr($str, 0, -1);
}
Update: Ok it is also possible without regular expressions using strrpos ans substr_replace:
$str = "A sentence with 'Testers' in it";
echo substr_replace($str,'', strrpos($str, 's'), 1);
// Ouputs: A sentence with 'Tester' in it
strrpos returns the index of the last occurrence of a string and substr_replace replaces a string starting from a certain position.
(Which is the same as Gordon proposed as I just noticed.)
All answers so far remove the last character of a word. However if you really want to replace the last occurrence of a character, you can use preg_replace with a negative lookahead:
$s = "A sentence with 'Testers' in it";
echo preg_replace("%s(?!.*s.*)%", "", $string );
// Ouputs: A sentence with 'Tester' in it
$result = rtrim($str, 's');
$result = str_pad($result, strlen($str) - 1, 's');
See rtrim()
Your question is somewhat unclear whether you want to remove the s from the end of the string or the last occurence of s in the string. It's a difference. If you want the first, use the solution offered by zerkms.
This function removes the last occurence of $char from $string, regardless of it's position in the string or returns the whole string, when $char does not occur in the string.
function removeLastOccurenceOfChar($char, $string)
{
if( ($pos = strrpos($string, $char)) !== FALSE) {
return substr_replace($string, '', $pos, 1);
}
return $string;
}
echo removeLastOccurenceOfChar('s', "the world's greatest");
// gives "the world's greatet"
If your intention is to inflect, e.g singularize/pluralize words, then have a look at this simple inflector class to know which route to take.
$str = preg_replace("/s$/i","",rtrim($str));
The very simplest solution is using rtrim()
That is exactly what that function is intended to be used for:
Strip whitespace (or other characters) from the end of a string.
Nothing simpler than that, I am not sure why, and would not follow the suggestions in this thread going from regex to "if/else" blocks.
This is your code:
$string = "Testers";
$stripped = rtrim( $string, 's' );
The output will be:
Tester