Replace string before a string? - php

Sorry, I'm bad English. I'm going to post my code now:
$image = 'http://example.com/thisisimage.gif';
$filename = substr($image, strrpos($image, '/') + 1);
echo '<br>';
echo $filename;
echo '<br>';
echo preg_replace('/^[^\/]+/', 'http://mydomain.com', $image);
echo '<br>';
$image is string;
$filename is image name (in example above, it returns 'thisisimage.gif')
Now i want replace all before $filename with 'http://mydomain.com', my code is above but it doesnt work.
Thanks!

$foo = explode($filename, $image);
echo $foo[0];
Explode "splits" one the given paramater ( in your case $filename ). It returns an array with where the keys are split on the string you gave.
And if you just want to change the url. you use a str_replace
$foo = str_replace("http://example.com", "http://localhost", $image);
//This will change "http://example.com" to "http://localhost", like a text replace in notepad.
In your case:
$image = 'http://example.com/thisisimage.gif';
$filename = substr($image, strrpos($image, '/') + 1);
$foo = explode($filename, $image);
echo '<br>';
echo $filename;
echo '<br>';
echo str_replace($foo[0], "http://yourdomain.com/", $url);
echo '<br>';

There's another approach in which you don't need a regular expression:
in Short:
$image = 'http://example.com/thisisimage.gif';
$url = "http://mydomain.com/".basename($image);
Explanation:
If you just want the file name without url's or directory path's, basename() is your friend;
$image = 'http://example.com/thisisimage.gif';
$filename = basename($image);
output: thisisimage.gif
Then you can add whatever domain you want:
$mydomain = "http://mydomain.com/";
$url = $mydomain.$filename;

Try this :
$image = 'http://example.com/thisisimage.gif';
echo preg_replace('/^http:\/\/.*\.com/', 'http://mydomain.com',$image);

This should simply work:
$image = 'http://example.com/thisisimage.gif';
$filename = substr($image, strrpos($image, '/') + 1);
echo '<br>';
echo $filename;
echo '<br>';
echo 'http://mydomain.com/'.$filename;
echo '<br>';

if you just like to add your own domain before the file name, try this:
$filename = array_pop(explode("/", $image));
echo "http://mydomain.com/" . $filename;
if you wanna only replace thedomain, try this:
echo preg_replace('/.*?[^\/]\/(?!\/)/', 'http://mydomain.com/', $image);

The other people here have given good answers about how to do it - regex has its advantages but also drawbacks - its slower, respectively requires more resources and for something simple as this, I would advice you to use the explode approach, but while speaking for regex functions you also may try this, instead your preg_replace:
echo preg_replace('#(?:.*?)/([^/]+)$#i', 'http://localhost/$1', $image);
It seems variable length positve lookbehind is not supported in PHP.

Related

How to create dynamic path using php variable?

I want to create a path with dynamic variable.
echo $path='App\Widgets\mywidgetname';
I want to replace mywidgetname then I have to put a variable like this
$path='App\Widgets\'.$widgetname; // (but this not working)
Try this,
$path = 'App\Widgets\mywidgetname';
$path = str_replace('mywidgetname', $widgetname, $path);
OR
$path = 'App\Widgets\mywidgetname';
$path = substr($path, 0, strrpos($path, "\\") + 1) . $widgetname;
You can use:
$path = sprintf("App\Widgets\%s", $widgetname);
echo $path;

Text after the last slash, what is my mistake?

I want to get out of the URL after the last slash "/" the text. The page URL is very variable, for example:
http://mydomain.com/colors/productname.html
(result is "productname") OK!
http://mydomain.com/colors/size/zip/shipment/
(result is "shipment") OK!
or
http://mydomain.com/colors/
(result is "null") Null!
It works well so far except for the last example. Once, just a slash "/" after the domain name is I get no result.
What is my mistake?
Thanks in advance!
$url = "variable"
if (strpos($url,'.h') !== false) {
$url = preg_replace('/\.h.*/', '/', $url);}
$url = rtrim($url, "/");
$str = substr(strrchr($url, '/'), 1);
$str = str_replace('-',' ',$str);
$keys = str_replace('/ /', '%20', $str);
$metric = urlencode($keys);
php already has a function that does this its called basename
$url = "http://mydomain.com/colors/";
echo basename($url);
//outputs
colors
$url = "http://mydomain.com/colors/productname.html";
echo basename($url);
//outputs
productname.html
What is stopping you from using basename?
<?php
$url = "http://mydomain.com/colors/";
$url = basename( $url ); //outputs "colors"
echo $url;
?>
Or if you dont want the ".html" in output, you can use pathinfo with PATHINFO_FILENAME flag
<?php
$url = "http://mydomain.com/colors.html";
$url = pathinfo( $url, PATHINFO_FILENAME ); //also outputs "colors"
echo $url;
?>

PHP Regex to remove everything but the date from filename

I have a filename with a date in it, the date is always at the end of the filename.
And there is no extension (because of the basename function i use).
What i have:
$file = '../file_2012-01-02.txt';
$file = basename('$file', '.txt');
$date = preg_replace('PATTERN', '', $file);
Im really not good at regex, so could someone help me with getting the date out of the filename.
Thanks
I suggest to use preg_match instead of preg_replace:
$file = '../file_2012-01-02';
preg_match("/.*([0-9]{4}-[0-9]{2}-[0-9]{2}).*/", $file, $matches);
echo $matches[1]; // contains '2012-01-02'
If there is always an underscore before the date:
ltrim(strrchr($file, '_'), '_');
^^^^^^^ get the last underscore of the string and the rest of the string after it
^^^^^ remove the underscore
I suggest you to try:
$exploded = explode("_", $filename);
echo $exploded[1] . '<br />'; //prints out 2012-01-02.txt
$exploded_again = explode(".", $exploded[1]);
echo $exploded_again[0]; //prints out 2012-01-02
Shorten it:
$exploded = explode( "_" , str_replace( ".txt", "", $filename ) );
echo $exploded[1];
With this, use regexp when you really need to :
current(explode('.', end(explode('_', $filename))));
This should help i think:
<?php
$file = '../file_2012-01-02.txt';
$file = basename("$file", '.txt');
$date = preg_replace('/(\d{4})-(\d{2})-(\d{2})$/', '', $file);
echo $date; // will output: file_
?>

removing last 3 characters on a file (file extension)

my file name are being stored in a variable $file_name... how can i remove the extension and just have the name only? is there something other than strcmp that i can use... that doesn't seem to do it
Use pathinfo.
<?php
$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // since PHP 5.2.0
?>
Note: If you're not on PHP >= 5.2 use this to compose the filename
$path_parts['filename'] = substr($path_parts['basename'], 0, -1*strlen($path_parts['extension'])-1);
You can do:
$file_name_no_ext = pathinfo($file_name , PATHINFO_FILENAME);
substr($file_name, 0, -4);
You could use regular expressions. Regular expression to remove a file's extension
You should take a look at the pathinfo() function.
Similar to #fire, but more robust in the face of multiple dots:
$comps = explode('.', $filename);
unset($comps[count($comps) - 1]);
$ext = implode('.', $comps);
I use:
$file_name = current(explode(".", $file_name));

altering a string with PHP

If I have filename.jpg, with PHP how would change it too filename123456789.jpg, where 123456789 is a timestamp, I currently do this,
$name = $filename;
$parts = explode(".", $name);
$filename = $parts[0].time().'.'.$parts[1];
however this just just leaves me with 123456789.
Your approach works fine too, but breaks if the filename has multiple dots. I'd rather use the pathinfo() function to accomplish this:
$info = pathinfo($filename);
$filename = $info['filename'].time().'.'.$info['extension'];
debug (output) your input and steps to find the error
function debug($var, $label = '') {
echo $label
. '<pre>'
. print_r($var, true)
. '</pre>';
}
$name = 'filename.bug.test.jpg';
debug($name, 'old filename');
$parts = explode('.', $name);
debug($parts, 'filenameparts');
$ext = array_pop($parts);
$prefix = implode('.', $parts);
$newName = $prefix . time() . '.' . $ext;
debug($newName, 'new filename');
as mention above use pathinfo instead of explode
i've used explode, couse i've used a dummy filename.
thats a no-brainer:
function getFileName($filename){
preg_match('#([^/]+)\.([\w]+)$#',$filename,$match);
return $match[1].time().'.'.$match[2];
}

Categories