PHP get first few charactors and remove from string - php

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"

Related

Remove empty space and plus sign from the beginning of a string

I have a string that begins with an empty space and a + sign :
$s = ' +This is a string[...]';
I can't figure out how to remove the first + sign using PHP. I've tried ltrim, preg_replace with several patterns and with trying to escape the + sign, I've also tried substr and str_replace. None of them is removing the plus sign at the beginning of the string. Either it doesn't replace it or it remplace/remove the totality of the string. Any help will be highly appreciated!
Edit : After further investigation, it seems that it's not really a plus sign, it looks 100% like a + sign but I think it's not. Any ideas for how to decode/convert it?
Edit 2 : There's one white space before the + sign. I'm using get_the_excerpt Wordpress function to get the string.
Edit 3 : After successfully removing the empty space and the + with substr($s, 2);, Here's what I get now :
$s == '#43;This is a string[...]'
Wiki : I had to remove 6 characters, I've tried substr($s, 6); and it's working well now. Thanks for your help guys.
ltrim has second parameter
$s = ltrim($s,'+');
edit:
if it is not working it means that there is sth else at the beginning of that string, eg. white spaces. You can check it by using var_dump($s); which shows you exactly what you have there.
You can use explode like this:
$result = explode('+', $s)[0];
What this function actually does is, it removes the delimeter you specify as a first argument and breaks the string into smaller strings whenever that delimeter is found and places those strings in an array.
It's mostly used with multiple ocurrences of a certain delimeter but it will work in your case too.
For example:
$string = "This,is,a,string";
$results = explode(',', $string);
var_dump($results); //prints ['This', 'is', 'a', 'string' ]
So in your case since the plus sign appears ony once the result is in the zero index of the returned array (that contains only one element, your string obviously)
Here's a couple of different ways I can think of
str_replace
$string = str_replace('+', '', $string);
preg_replace
$string = preg_replace('/^\+/', '', $string);
ltrim
$string = ltrim($string, '+');
substr
$string = substr($string, 1);
try this
<?php
$s = '+This is a string';
echo ltrim($s,'+');
?>
You can use ltrim() or substr().
For example :
$output = ltrim($string, '+');
or you can use
$output = substr($string, 1);
You can remove multiple characters with trim. Perhaps you were not re-assigning the outcome of your trim function.
<?php
$s = ' +This is a string[...]';
$s = ltrim($s, '+ ');
print $s;
Outputs:
This is a string[...]
ltrim in the above example removes all spaces and addition characters from the left hand side of the original string.

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;

How to combine this regex into one

I am trying to extract the last word of a string but ignoring any extension it may have
e.g. amazon_uk instead of amazon_uk.gif
The following code extracts the word from the string using 2 preg_match functions, I want to be able to do the same thing in 1 preg_match, how can I do this?
php code
$str = 'http://i.example.com/about/bs/logo_borderless/amazon_uk.gif';
preg_match('/[^\.\/]+\.[^\.\/]+$/', $str, $matches);
preg_match('/^[^.]+(?=.)/', $matches[0], $matches2);
$website = $matches2[0];
output
amazon_uk
preg_match( '#/([^./]+)\.[^./]+$#si', $str, $matches );
Here's what it's doing...
/
match a forward slash
([^./]+)
Then one or more of neither a period or forward slash. This is the bit we're matching.
\.
Then a period
[^./]+
Then one or more of neither a period or forward slash again.
$
Then the end of the string
You asked about a regex, so that's above. But here's what I'd actually do...
$url = 'http://i.example.com/about/bs/logo_borderless/amazon_uk.gif';
$output = str_replace( array('.gif','.jpg','.png'), '', basename($url) );
Basename's something I use all the time - very handy.
Because it will always be in the format you specified (per a comment), you can also use a combination of substr() and strpos() (and strrpos()) to get the text as opposed to regex:
// get the filename after the last slash
$file = substr($str, strrpos($str, '/') + 1);
// get the text before the extension
$website = substr($file, 0, strpos($file, '.'));
preg_match('/\/([\w]+)\.(?:[a-zA-Z]{1,3})$/', $str, $matches);
$result = $matches[1];
A non-greedy search plus a optional match on the extension should do the trick:
preg_match('/([^\.\/]+?)(?:\.\w*)?$/', $str, $matches);
$website = $matches[1];

First instance in string

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

Categories