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
Related
I have a string "Hello World !" and I want to replace some letters in it and receive result like "He!!! W!r!d !" it's means that i changed all "l" and "o" to "!"
I found function preg_replace();
function replace($s){
return preg_replace('/i/', '!', "$s");
}
and it works with exactly one letter or symbol, and I want to change 2 symbols to "!".
Change your function as such;
function replace($s) {
return preg_replace('/[ol]/', '!', $s);
}
Read more on regular expressions here to get further understanding on how to use regular expressions.
Since you are already using regular expressions, why not really use then to work with the pattern you are really looking for?
preg_replace('/l+/', '!', "Hello"); // "He!o" ,so rewrites multiple occurances
If you want exactly two occurances:
preg_replace('/l{2}/', '!', "Helllo"); // "He!lo" ,so rewrites exactly two occurances
Or what about that:
preg_replace('/[lo]/', '!', "Hello"); // "He!!!" ,so rewrites a set of characters
Play around a little using an online tool for such: https://regex101.com/
This can be accomplished either using preg_replace() like you're trying to do or with str_replace()
Using preg_replace(), you need to make use of the | (OR) meta-character
function replace($s){
return preg_replace('/l|o/', '!', "$s");
}
To do it with str_replace() you pass all the letters that you want to replace in an array, and then the single replacing character as just a string (or, if you want to use multiple replacing characters, then also pass an array).
str_replace(array("l","o"), "!", $s);
Live Example
Using preg_replace like you did:
$s = 'Hello World';
echo preg_replace('/[lo]/', '!', $s);
I think another way to do it would be to use an array and str_replace:
$s = 'Hello World';
$to_replace = array('o', 'l');
echo str_replace($to_replace, '!', $s);
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 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;
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))
How can I get the value between the {} eg. 1 in "{1}" and use it?
if (preg_match('/\{(\d+)\}/', $str, $mtch))
echo $mtch[1];
where $str is '{1}'
If you just want to get rid of the brackets, you may use trim() function
$str = "{1}";
$str = trim($str, "{}");
echo $str; //output: 1
EDIT: I removed the comma - "{}" is enough as the secont parameter for trim() (was "{,}" before the edit)
You can use a preg_replace function to perform a regular expression.
What exactly do you need to do the string.
If you want to get a certain character of the string, $str = '{1}'; $str[1] will return the 2nd character of the string.
Depends on what you actually have .. in the example above this would be enough:
$number = $string{1};
But i guess you need more something like
preg_match('/{([0-9]+)}/', $string, $matches);
$number = $matches[1];