First instance in string - php

I have a string, say:
www.google.com/tomato.mdm
I need to replace tomato with tomaton (add n to it). My method is to find the . then replace it with n. . This didn't work. Tomato can be many differeny words, so I can't just search for that either...
Is their any way to solve this?
I thought about only replacing it at the first instance from the end, but cannot find a function to do this in the php manuel.

I would approach it like this:
$string = "www.google.com/tomato.mdm";
$lastDot = strrpos($string, '.');
$newString = substr($string, 0, $lastDot) . 'n.' . substr($string, $lastDot + 1);
I use strrpos to find the last occurrence of "." in the string. Then I split the string in two parts (using substr): Everything before the last dot, and everything after it. I then insert "n." between those two parts, which should give the desired result.
A solution using regular expression would be the following:
$string = "www.google.com/tomato.mdm";
$newString = preg_replace('/(.*?)(\.[^\.]*)$/', '\1n\2', $string);
See preg_replace and a regex reference for more info.

You should use Regex to do this
$newStr = preg_replace("#^(www.google.com/[a-zA-z]*)#", '$1n', "www.google.com/tomato.mdm");

Related

PHP wrapping last two letters of string with HTML

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.

Cut string from end to specific char in php

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));

how to remove last occurance of underscore in string

I have a string that contains many underscores followed by words ex: "Field_4_txtbox" I need to find the last underscore in the string and remove everything following it(including the "_"), so it would return to me "Field_4" but I need this to work for different length ending strings. So I can't just trim a fixed length.
I know I can do an If statement that checks for certain endings like
if(strstr($key,'chkbox')) {
$string= rtrim($key, '_chkbox');
}
but I would like to do this in one go with a regex pattern, how can I accomplish this?
The matching regex would be:
/_[^_]*$/
Just replace that with '':
preg_replace( '/_[^_]*$/', '', your_string );
There is no need to use an extremly costly regex, a simple strrpos() would do the job:
$string=substr($key,0,strrpos($key,"_"));
strrpos — Find the position of the last occurrence of a substring in a string
You can also just use explode():
$string = 'Field_4_txtbox';
$temp = explode('_', strrev($string), 2);
$string = strrev($temp[1]);
echo $string;
As of PHP 5.4+
$string = 'Field_4_txtbox';
$string = strrev(explode('_', strrev($string), 2)[1]);
echo $string;

Find and replace starting from the end [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Preg Replace - replace second occurance of a match
I have a string that includes the word rules twice. I need to find and replace the 2nd word. Tried fooling around with str_replace() but couldn't get anything, the 4th parameter wasn't what I expected.
Here is an example string:
http://localhost/proj1/modstart/admin/index.php?i=rules&sid=397ab1f6b8eb8a17787438a7e2e60ea3&mode=rules
After my replace it should look like this:
http://localhost/proj1/modstart/admin/index.php?i=rules&sid=397ab1f6b8eb8a17787438a7e2e60ea3&mode=manage
I read that preg_replace() could help, but I don't know how to write patterns.
Ideas?
P.S: Don't suggest splitting the string into two variables, that wouldn't serve my needs.
It would be a very good idea to learn about regular expressions. In PHP, you can accomplish your find/replace like this:
$result = preg_replace('/(rules.*?)rules/','$1manage',$str,1);
It basically finds "rules" once, then anything, then rules a second time, then puts it all back before the second match and replaces the word.
To not use a regular expression, and also to not store anything into a second variable, you could use str_replace() with a little magic from strpos():
$string = substr($string, 0, strpos($str, 'rules') + 5) . str_replace('rules', 'whatever', substr($string, strpos($string, 'rules') + 5));
This will take the full string up-to the end of the first instance of rules and then do the string-replacement on the second-part of the string which will contain any other instance of the word.
The same thing, but a little more cleaner (yes, by using a second variable):
$pos = strpos($string, 'rules') + 5;
$string = substr($string, 0, $pos) . str_replace('rules', 'whatever', substr($string, $pos));
If the word to find+replace is dynamic or you want to use a different word on different pages, you could make that a variable, like this:
$findMe = 'rules';
$replaceWith = 'whatever';
$pos = strpos($string, $findMe) + strlen($findMe);
$string = substr($string, 0, $pos) . str_replace($findMe, $replaceWith, substr($string, $pos));
You should use regex >>
$new = preg_replace('/\brules\b(?!.*\brules\b)/', 'manage', $old);
It is a good idea to use word boundaries \b, so it will not match some larger strings that contain "rules", such as "preudorules".
Negative lookahead (?!.*\brules\b) ensures there is no other word "rules" behind, so the one you are replacing is the last one.

PHP get first few charactors and remove from string

Does anyone know how to remove the first few characters from a string and remove them in PHP.
Like in the string "str_filename" I need to remove the "str_" and save the "filename".
But it has to remove as many charactors as it takes to get to the "_".
In other words, i need to remove all the characters up until and including the first "_" in the string.
You can do this:
if (strpos($string, '_') !== false)
$string = substr($string, strpos($string, '_') + 1);
It works as you can see here: http://codepad.org/g12ENLGY
Note: The if is useful because your string could not have the '_' char.
Could you use something like:
$files = explode("_", $filename);
echo $files[1];
So this would split the string on the _ character, and then echo the second part (after the underscore).
This assumes that there is only one underscore though.
Please see http://www.php.net/manual/en/function.explode.php
An additional solution than using explode and substr as have been mentioned you can solve it using regex:
^(?:[^_]*_)(.*)$
Here's an example using it:
$str = "str_filename";
$pattern = "/^(?:[^_]*_)(.*)$/";
preg_match($pattern, $str, $matches);
echo $matches[1]; //prints "filename"

Categories