Let's say I have a string like:
Cant_Hold_Us_-_Fingerstyle_Guitar_0.mp3
How can I get rid of _0.mp3 dynamically with PHP? The values are not hard-coded for the current example. Maybe if i use explode?
$old = "your file name here";
$new = substr($old, 0, strrpos($old, "_"));
The substr method will take only the part of the string that you want.
The strrpos method finds the last index of the underscore and passes that number into the substr method so that it knows how far to cut. This method is ideal because rather than hardcoding a specific value, the script will dynamically change for each file, just as you suggested.
Just a bit of warning: if the file name does not contain an underscore, the method won't know where to cut to and will cause error in execution. A good bit of practice would be checking if (strrpos($old, "_") !== false).
I like Confiqure's answer. To complement, you could also use a regular expression if you find that you need more power.
$old = "Cant_Hold_Us_-_Fingerstyle_Guitar_0.mp3";
$new = preg_replace('/_\d+\.mp3$/', '', $old);
Regex is your friend. Have a look at preg_match and / or preg_replace.
$title = preg_replace("/_[0-9]+\.mp3$/i", "", $x);
Works for blablabla_21.mp3 as well....
Related
I seek your assistance once more with a small problem I am having, the solution is potentially obvious/looking at me in the face, but I have yet to resolve my issue.
I have the need to trim a string which happens to have a variable within it. (the string is actually a URL)
An example String/URL:
/portal/index.php?module=SerialDB&page=listing&returnmsg=3
&returnmsg=3 can be a range of numbers from 0 to 100, as well as, in some cases, text. This is the variable I need to trim as I am hoping to store the rest of the string/URL into a database. The following is the result I seek;
/portal/index.php?module=SerialDB&page=listing
I have tried the following code just to see if it could appropriate the function I require, but unfortunately it is more specific and won't trim unless it gets an EXACT match.
$str = "/portal/index.php?module=SerialDB&returnmsg=3";
echo $str . "<br>"; // Test to see full string
echo chop($str,"&returnmsg="); // Attempt to trim the string
If anyone is up to the task of assisting I would be greatly appreciative. As with all my questions, I would also like to understand what is happening as opposed to just being handed the code so I can use it confidently in the future.
Thanks once again guys :)
A quick way that doesn't depend on parameter order is just to take apart the pieces, pick out what you want, and then put them back together again (you can look up the various PHP functions for more details):
$urlParts = parse_url($url);
parse_str($urlParts['query'], $queryParts);
$returnMsg = $queryParts['returnmsg'];
unset($queryParts['returnmsg']);
$urlParts['query'] = http_build_query($queryParts);
$url = http_build_url($urlParts);
Simple. The concept is known as slicing.
$url = "/portal/index.php?module=SerialDB&page=listing&returnmsg=3";
$new_url = substr( $url, 0, strrpos( $url, '&') );
result is: /portal/index.php?module=SerialDB&page=listing
The substr() function returns part of a string. It takes three parameters. Parameter #1 is the string you are going to extract from, parameter #2 is where are you going to start from and parameter #3 is the length of the slice or how many characters you want to extract.
The strrpos() function returns the position/index of the last occurrence of a substring in a string. Example: if you have the string "zazz" the position of the last z will be returned. You can think of it as "string reverse position". This function accepts three parameters. I will only cover two as this is the number I used in this example. Parameter #1 is the string you are searching in, parameter #2 is the needle or what you are looking for, in your case the &. As I mentioned in the beginning of this paragraph, it returns the position in the form of an integer. In your case that number was 46.
So the strrpos() as the third parameter in substr() is telling it up to where to slice the string. Upon completion it returns the segment that you wanted to extract.
It would be helpful if you read the PHP Manual and looked over the available functions that might help you in the future. You can combine these functions in various ways to solve your problems.
http://php.net/manual/en/funcref.php
If returnmsg is always the last param (and not the first) in your url and if your url doesn't contain an anchor, so in short the param is always at the end, you can solve the problem with a simple explode:
$url = explode('&returnmsg=', $url)[0];
(you split the string with &returnmsg= and you keep the first part).
otherwise as suggested in comments you can use a regex replacement:
$url = preg_replace('~[?&]returnmsg=[^&#]*~', '', $url);
pattern details:
~ # pattern delimiter
[?&] # a literal "?" or a literal "&"
returnmsg=
[^&#]* # any characters except "&" or "#" zero or more times
~
(for the two ways, if the param is not present, the url stay unchanged.)
I don't weather it comes in starting or in end so if it comes in end then use the code below.
<?php
$url="/portal/index.php?module=SerialDB&page=listing&returnmsg=3";
$array= explode("&",$url);
$new_url="";
foreach($array as $p){
if(strpos($p,"returnmsg")===false){
$new_url .=$p."&";
}
}
echo rtrim($new_url, "&");
The above code is exploding the array & and then running a foreach loop to join them.
#Bobdye answer is also correct but there is a bit problem in that code, that wasn't running for me. Use the code below
<?php
$url="/portal/index.php?module=SerialDB&page=listing&returnmsg=3";
$urlParts = parse_url($url);
parse_str($urlParts['query'], $queryParts);
$returnMsg = $queryParts['returnmsg'];
unset($queryParts['returnmsg']);
$urlParts['query'] = http_build_query($queryParts);
$url = http_build_query($urlParts);
var_dump($url);
Hope this helps you
So I've seen a couple articles that go a little too deep, so I'm not sure what to remove from the regex statements they make.
I've basically got this
foo:bar all the way to anotherfoo:bar;seg98y34g.?sdebvw h segvu (anything goes really)
I need a PHP regex to remove EVERYTHING after the colon. the first part can be any length (but it never contains a colon. so in both cases above I'd end up with
foo and anotherfoo
after doing something like this horrendous example of psuedo-code
$string = 'foo:bar';
$newstring = regex_to_remove_everything_after_":"($string);
EDIT
after posting this, would an explode() work reliably enough? Something like
$pieces = explode(':', 'foo:bar')
$newstring = $pieces[0];
explode would do what you're asking for, but you can make it one step by using current.
$beforeColon = current(explode(':', $string));
I would not use a regex here (that involves some work behind the scenes for a relatively simple action), nor would I use strpos with substr (as that would, effectively, be traversing the string twice). Most importantly, this provides the person who reads the code with an immediate, "Ah, yes, that is what the author is trying to do!" instead of, "Wait, what is happening again?"
The only exception to that is if you happen to know that the string is excessively long: I would not explode a 1 Gb file. Instead:
$beforeColon = substr($string, 0, strpos($string,':'));
I also feel substr isn't quite as easy to read: in current(explode you can see the delimiter immediately with no extra function calls and there is only one incident of the variable (which makes it less prone to human errors). Basically I read current(explode as "I am taking the first incident of anything prior to this string" as opposed to substr, which is "I am getting a substring starting at the 0 position and continuing until this string."
Your explode solution does the trick. If you really want to use regexes for some reason, you could simply do this:
$newstring = preg_replace("/(.*?):(.*)/", "$1", $string);
A bit more succinct than other examples:
current(explode(':', $string));
You can use RegEx that m.buettner wrote, but his example returns everything BEFORE ':', if you want everything after ':' just use $2 instead of $1:
$newstring = preg_replace("/(.*?):(.*)/", "$2", $string);
You could use something like the following. demo: http://codepad.org/bUXKN4el
<?php
$s = 'anotherfoo:bar;seg98y34g.?sdebvw h segvu';
$result = array_shift(explode(':', $s));
echo $result;
?>
Why do you want to use a regex?
list($beforeColon) = explode(':', $string);
In PHP 5.3 there is a nice function that seems to do what I want:
strstr(input,"\n",true)
Unfortunately, the server runs PHP 5.2.17 and the optional third parameter of strstr is not available. Is there a way to achieve this in previous versions in one line?
For the relatively short texts, where lines could be delimited by either one ("\n") or two ("\r\n") characters, the one-liner could be like
$line = preg_split('#\r?\n#', $input, 2)[0];
for any sequence before the first line feed, even if it an empty string,
or
$line = preg_split('#\r?\n#', ltrim($input), 2)[0];
for the first non-empty string.
However, for the large texts it could cause memory issues, so in this case strtok mentioned below or a substr-based solution featured in the other answers should be preferred.
When this answer was first written, almost a decade ago, it featured a few subtle nuances
it was too localized, following the Opening Post with the assumption that the line delimiter is always a single "\n" character, which is not always the case. Using PHP_EOL is not the solution as we can be dealing with outside data, not affected by the local system settings
it was assumed that we need the first non-empty string
there was no way to use either explode() or preg_split() in one line, hence a trick with strtok() was proposed. However, shortly after, thanks to the Uniform Variable Syntax, proposed by Nikita Popov, it become possible to use one of these functions in a neat one-liner
but as this question gained some popularity, it's better to cover all the possible edge cases in the answer. But for the historical reasons here is the original solution:
$str = strtok($input, "\n");
that will return the first non-empty line from the text in the unix format.
However, given that the line delimiters could be different and the behavior of strtok() is not that straight, as "Delimiter characters at the start or end of the string are ignored", as it says the man page for the original strtok() function in C, now I would advise to use this function with caution.
It's late but you could use explode.
<?php
$lines=explode("\n", $string);
echo $lines['0'];
?>
$first_line = substr($fulltext, 0, strpos($fulltext, "\n"));
or something thereabouts would do the trick. Ugly, but workable.
try
substr( input, 0, strpos( input, "\n" ) )
echo str_replace(strstr($input, '\n'),'',$input);
list($line_1, $remaining) = explode("\n", $input, 2);
Makes it easy to get the top line and the content left behind if you wanted to repeat the operation. Otherwise use substr as suggested.
not dependent from type of linebreak symbol.
(($pos=strpos($text,"\n"))!==false) || ($pos=strpos($text,"\r"));
$firstline = substr($text,0,(int)$pos);
$firstline now contain first line from text or empty string, if no break symbols found (or break symbol is a first symbol in text).
try this:
substr($text, 0, strpos($text, chr(10)))
You can use strpos combined with substr. First you find the position where the character is located and then you return that part of the string.
$pos = strpos(input, "\n");
if ($pos !== false) {
echo substr($input, 0, $pos);
} else {
echo 'String not found';
}
Is this what you want ?
l.e.
Didn't notice the one line restriction, so this is not applicable the way it is. You can combine the two functions in just one line as others suggested or you can create a custom function that will be called in one line of code, as wanted. Your choice.
Many times string manipulation will face vars that start with a blank line, so don't forget to evaluate if you really want consider white lines at first and end of string, or trim it. Also, to avoid OS mistakes, use PHP_EOL used to find the newline character in a cross-platform-compatible way (When do I use the PHP constant "PHP_EOL"?).
$lines = explode(PHP_EOL, trim($string));
echo $lines[0];
A quick way to get first n lines of a string, as a string, while keeping the line breaks.
Example 6 first lines of $multilinetxt
echo join("\n",array_splice(explode("\n", $multilinetxt),0,6));
Can be quickly adapted to catch a particular block of text, example from line 10 to 13:
echo join("\n",array_splice(explode("\n", $multilinetxt),9,12));
there is a string, for example : http://address.com/sef-title-of-topic-1111.html
i could not get 1111 in anyway with regexp in php. Is it possible? How?
my code:
$address = 'http://address.com/sef-title-of-topic-1111.html';
preg_match('#-(.*?)\.html#sim',$address,$result);
If the url example is how they will always appear (ie. ending in hyphen, numbers, .html) then this should work:
$str = "http://address.com/sef-title-of-topic-1111.html";
preg_match('#.*-(\d+)\.html#', $str, $matches);
print_r($matches);
If they won't always match the pattern you gave in your question, then clarify by showing alternative values for your $address value.
If you know that the extension is definitely .html (and not .htm for example) then you could use
$lastNos= substr($input, -9, -4);
Clearly a simple solution but you have not specified why regex is required.
If the URL will always be in this format I would use str_replace to strip the .html then explode by "-" and find the last piece.
Of course all of that is assuming the URL is always in this format.
If the format is always the same you dont need a regex.
$url = "http://address.com/sef-title-of-topic-1111.html";
echo $str = strrev(array_shift(array_reverse(explode(".", array_shift(explode("-",strrev($url)))))));
edit: sorry my php is a bit rusty
is there a great way to extract subdomain with php without regex ?
why without regex ?
there are a lot of topic about this, one if them is Find out subdomain using Regular Expression in PHP
the internet says it consumes memory a
lot, if there is any consideration or
you think better use regex ( maybe we
use a lot of function to get this
solution ) please comment below too.
example
static.x.com = 'static'
helloworld.x.com = 'helloworld'
b.static.ak.x.com = 'b.static.ak'
x.com = ''
www.x.com = ''
Thanks for looking in.
Adam Ramadhan
http://php.net/explode ?
Just split them on the dot? And do some functions?
Or if the last part (x.com) is the same everytime, do a substring on the hostname, stripping of the last part.
The only exception you'll have to make in your handling is the www.x.com (which technically is a subdomain).
$hostname = '....';
$baseHost = 'x.com';
$subdomain = substr($hostname, 0, -strlen($baseHost));
if ($subdomain === 'www') {
$subdomain = '';
}
Whoever told you that regexes "consume a lot" was an idiot. Simple regexes are not very cpu/memory-consuming.
However, for your purpose a regex is clearly overkill. You can explode() the string and then take as many elements from the array as you need. However, your last example is really bad. www is a perfectly valid subdomain.
You can first use parse_url http://www.php.net/manual/de/function.parse-url.php
and than explode with . as delimiter on the host http://www.php.net/manual/de/function.explode.php
I would not say it is quicker (just test it), but maybe this solution is better.
function getSubdomain($host) {
return implode('.', explode('.', $host, -2));
}
explode splits the string on the dot and drops the last two elements. Then implode combines these pieces again using the dot as separator.