Given the following URL:
http://www.domain.com/reporting/category-breakdown.php?re=updated
I need to remove everything after the .php
It might be "?re=updated" or it could be something else. The number of characters won't always be the same, the string will always end with .php though.
How do I do this?
To find the first position of a substring in a string you can use strpos() in PHP.
$mystring = 'http://www.domain.com/reporting/category-breakdown.php?re=updated';
$findme = '.php';
$pos = strpos($mystring, $findme);
After, you have the position of the first character of your substring '.php' in your URL. You want to get the URL until the end of '.php', that means the position you get + 4 (substring length). To get this, you can use substr(string,start,length) function.
substr($mystring, 0, $pos + 4);
Here you are!
Find the first indexOf (".php"), then use substring from char 0 to your index + the length of (".php");
3 line solution:
$str = "http://www.domain.com/reporting/category-breakdown.php?re=updated";
$str = array_shift(explode('?', $str));
echo $str;
Note: it's not fool-proof and could fail in several cases, but for the kind of URLs you mentioned, this works.
Here is another way to get the non-query-string part of a url with PHP:
$url = 'http://www.domain.com/reporting/category-breakdown.php?re=updated';
$parsed = parse_url($url);
$no_query_string = $parsed['scheme'] . '://' . $parsed['hostname'] . $parsed['path'];
// scheme: http, hostname: www.domain.com, path: /reporting/category-breakdown.php
That will handle .php, .phtml, .htm, .html, .aspx, etc etc.
Link to Manual page.
Related
I have a path "../uploads/e2c_name_icon/" and I need to extract e2c_name_icon from the path.
What I tried is using str_replace function
$msg = str_replace("../uploads/","","../uploads/e2c_name_icon/");
This result in an output "e2c_name_icon/"
$msg=str_replace("/","","e2c_name_icon/")
There is a better way to do this. I am searching alternative method to use regex expression.
Try this. Outputs: e2c_name_icon
<?php
$path = "../uploads/e2c_name_icon/";
// Outputs: 'e2c_name_icon'
echo explode('/', $path)[2];
However, this is technically the third component of the path, the ../ being the first. If you always need to get the third index, then this should work. Otherwise, you'll need to resolve the relative path first.
Use basename function provided by PHP.
$var = "../uploads/e2c_name_icon/";
echo basename( $var ); // prints e2c_name_icon
If you are strictly want to get the last part of the url after '../uploads'
Then you could use this :
$url = '../uploads/e2c_name_icon/';
$regex = '/\.\.\/uploads\/(\w+)/';
preg_match($regex, $url, $m)
print_r ($m); // $m[1] would output your url if possible
You can trim after the str_replace.
echo $msg = trim(str_replace("../uploads/","","../uploads/e2c_name_icon/"), "/");
I don't think you need to use regex for this. Simple string functions are usually faster
You could also use strrpos to find the second last /, then trim off both /.
$path = "../uploads/e2c_name_icon/";
echo $msg = trim(substr($path, strrpos($path, "/",-2)),"/");
I added -2 in strrpos to skip the last /. That means it returns the positon of the / after uploads.
So substr will return /e2c_name_icon/ and trim will remove both /.
You'd be much better off using the native PHP path functions vs trying to parse it yourself.
For example:
$path = "../uploads/e2c_name_icon/";
$msg = basename(dirname(realpath($path))); // e2c_name_icon
This may be a dupe, but I cannot seem to find a thread which matches this issue. I want to remove all chars from a string after a given sub-string - but the chars and the number of chars after the sub-string is unknown. Most solutions I have found seem to only work for removing the given sub-string itself or a fixed length after a given sub-string.
I have
$str = preg_replace('(.gif*)','.gif$',$str);
Which locates 'blahblah.gif?12345' ok, but I cannot seem to remove the chars after the sub-string '.gif'. I read that $ denotes EOS so I thought this would work, but apparently not. I also tried
'.gif$/'
and simply
'.gif'
It can be done without regex:
echo substr('blahblah.gif?12345', strpos('blahblah.gif?12345', '.gif') + 4);
// returns ?12345 this is the length of the substring ^
So the code is:
$str = 'original string';
$match = 'matching string';
$output = substr($str, strpos($str, $match) + strlen($match));
Ok, now I'm not sure if you want to keep the first or the second part of the string. Anyway, here's the code for keeping the first part:
echo substr('blahblah.gif?12345', 0, strpos('blahblah.gif?12345', '.gif') + 4);
// returns blahblah.gif ^ this is the key
And the full code:
$str = 'original string';
$match = 'matching string';
$output = substr($str, 0, strpos($str, $match) + strlen($match));
See the both examples work here: http://ideone.com/Ge30rY
Assuming (from OP's comment) that you are working with actual URLs as your source string, I believe that the best course of action here would be to use PHP's built-in functionality for working with and parsing URLs. You do this by using the parse_url() function:
(PHP 4, PHP 5)
parse_url — Parse a URL and return its components
This function parses a URL and returns an associative array containing any of the various components of the URL that are present.
This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial URLs are also accepted, parse_url() tries its best to parse them correctly.
From your example: www.page.com/image.gif?123 (or even just image.gif?123) using parse_url() will look something like this:
var_dump( parse_url( "www.page.com/image.gif?123" ) );
array(2) {
["path"]=>
string(22) "www.page.com/image.gif"
["query"]=>
string(3) "123"
}
As you can see, without the need for regular expressions or string manipulations we have broken up the URL into it's separate components. No need to re-invent the wheel. Nice and clean :)
You could do this:
$str = "somecontent.gif?anddata";
$pattern = ".gif";
echo strstr($str,$pattern,true).$pattern;
// Set up string to search through
$haystack = "blahblah.gif?12345";
// Determine substring and length of it
$needle = ".gif";
$length = strlen($needle);
// Find position of last substring
$location = strrpos($haystack, $needle);
// Use location of last occurence + it's length to get new string
$newtext = substr($haystack, 0, $location+$length);
I have a text.
$text='userpics/115/X3WGOC0009JA.jpg';
I want to add a letter p before X3WGOC0009JA.jpg, so my output will be
$text='userpics/115/pX3WGOC0009JA.jpg';
---^
I am new to php, so I don't really know what to try, I was hoping you could guide me in the right direction
You can explode by the slash by one way.
$exploded_text = explode('/', $text);
$new_text = $exploded_text[0] . $exploded_text[1] . 'p' . $exploded_text[2];
It's not the best way, but it will work.
Based on his question, I think all he wants to do is:
$text='userpics/115/'.'p'.'X3WGOC0009JA.jpg';
First, I would get the filename using strrpos and substr:
$text = 'userpics/115/X3WGOC0009JA.jpg';
$prepend_filename = 'p';
$last_slash_pos = strrpos($text, '/');
if ($last_slash_pos === false) throw new Exception('No slashes found');
$path = substr($text, 0, $last_slash_pos);
$filename = substr($text, $last_slash_pos + 1); // Add one to skip slash
And then you can add the p (as specified in $prepend_filename) using this:
$new_path = $path . DIRECTORY_SEPARATOR . $prepend_filename . $filename;
Have you tried just setting you variables and concatenation if you doing this a bunch.
$p = 'p';
$new = "userpics/115/" . $p . "X3WGOC0009JA.jpg";
There is a function, substr_replace(), which can insert a string at a point you want.
We combine this with strRpos() which we can use to find the first slash, LOOKING IN REVERSE:
$string = substr_replace($string, 'p', strrpos($string, '/')+1 );
This will insert 'p' in $string. At the position of the '/' in $string. The +1 corrects the 'cursor' to the character AFTER the slash.
Why not use the explode functions?
Very simple: Those are slow. String functions like strpos() and substr_replace() are VERY fast, especially on small strings.
Arrays are WAY slower in php, so don't go there unless you have to. For simple string- manipulation you should use simple string functions (sounds easy when you put it like that doesnt it?).
In a simple test I benchmarked the explode variant like user3758531's VS the string variant like mine:
100.000 tries with arrays: 1.5 sec
100.000 tries with strings: 0.9 sec
In this one situation, with this one action timing doesnt really matter. But apply this way of thinking thoughout the website and you will notice it speeding up/slowing down.
I'm trying to transform any URL in PHP and add a root folder onto it using regex.
Before:
http://domainNamehere.com/event/test-event-in-the-future/
After:
http://domainNamehere.com/es/event/test-event-in-the-future/
Any ideas?
A simple solution without regex:
$root_folder = 'es';
$url = "http://domainNamehere.com/event/test-event-in-the-future/";
$p = strpos($url, '/', 8);
$url_new = sprintf('%s/%s/%s', substr($url, 0, $p), $root_folder, substr($url, $p+1));
EDIT: JavaScript solution is pretty much the same:
var root_folder = 'es';
var url = "http://domainNamehere.com/event/test-event-in-the-future/";
var p = url.indexOf('/', 8);
var url_new = url.substring(0,p) + '/' + root_folder + url.substring(p);
Of course, for a live application you should also check if p actually gets a valid value assigned (that means if the slash is found) because you might have an invalid url in your input or empty string.
$url = 'http://domainNamehere.com/event/test-event-in-the-future/'; //or the function you use to grab it;
$url = str_replace('domainNamehere.com','domainNamehere.com/es', $url);
quite dirty but effective and without regex, assuming your "es" folder is always in that position (I think so)
If the domain name is always the same you can use:
$string = str_replace('domainNamehere.com', 'domainNamehere.com/es', $url);
Untested:
$url = preg_replace('#(?<=^[a-z]+://[^/]+/)#i', "es/", $url);
Use '#' to delimit the regular expression so the slashes don't have to be escaped.
(?<=...) searches for a match for [a-z]://[^/]+/ without including it in the matched string.
[a-z]+://[^/]/ matches a sequence of letters followed by :// followed by non-slashes, then a slash. This will handle all web protocols, particularly http and https.
The little i makes the search case-insensitive.
The replacement just inserts es/ after the match.
This is the most succinct way that I could think of how to do it.
$new_url = preg_replace('#(?<=\w)(?=/)#', '/en', $url, 1);
It will insert whatever you put in the 2nd parameter into the string just before the first slash that also has a proceeding alphanumeric character.
Tested with PHP 5.3.6
Let's say I have a string like so:
$file = 'widget-widget-newsletter.php';
I want to use preg_replace() to remove the prefix widget- and to remove the suffix .php . Is it possible to use one regular expression to achieve all this?
The resulting string should be widget-newsletter.
$file = preg_replace('/^widget-|\.php$/', '', $file);
Why not use substr? Much simpler and faster.
Don't think of it as stripping off the ends, rather as extracting the middle:
$file = 'widget-widget-newsletter.php';
if (preg_match('/^widget\-(.+)\.php$/i', $file, $matches))
echo "filename is " . $matches[1][0];
Of course, if "widget-" and ".php" are entirely static and are always going to be there, you could just use substr:
echo "filename is " . substr($file, 7, -4);
That would be much faster but if you pass it garbage, you'll get garbage back.
$name = preg_replace(array('%^widget-%', '%-%', '%\.php$%'), array('','_',''), $file);
should do it.
Or more general (assuming the prefix goes to the first - and the suffix starts at the last .):
$name = preg_replacearray('%^.*?-%', '%-%', '%\.(?!.*?\.).*?$%'), array('','_',''), $file);
If you provide an array of patterns and an array of replacements to the function, then each pattern gets replaced by the according replacement.
Update:
As you removed the requirement to replace the - by _, substr() is indeed better suited:
$name = substr($file, 7, -4);
From the manual description of the replacement parameter:
The string or an array with strings to replace. If this parameter is a string and the pattern parameter is an array, all patterns will be replaced by that string.
Sounds like you could use an array with the prefix and suffix patterns in it for the pattern parameter, and just put empty string as the replacement.