I want to replace the url in the following text with [FILENAME], where FILENAME is the name of the file.
check out this car http://somesite/ford.png
This will then appear like:
check out this car [ford]
This is my code so far:
$text = $_POST['text']; //get submitted post
$link = strstr($text, 'http://'); //look for an http
$filename = pathinfo ($link, PATHINFO_FILENAME); //get filename from $link
$result = str_replace($text,$link,"[".$filename."]"); // search on $text, find $link, replace it with $filename
echo $result;
At the moment, I am only getting back [ford], where is all the other text?
Using str_replace
You have your parameters in the wrong order, you need to change them like so:
$result = str_replace($link,"[".$filename."]",$text);
See here for documentation.
Alternative (Regular Expression)
You could use a regular expression. This method is marginly slower, but it will use less code:
$result = preg_replace('/http(s?):\/\/[a-z]\/(.+)\.png/i', '[$1]', $text);
You can then alter your regular expression further by allowing other kinds of images like so:
$result = preg_replace('/http(s?):\/\/[a-z]\/(.+)\.(png|gif|jpg|jpeg)/i', '[$1]', $text);
To Conclude
You can use either of the above methods, but in my opinion I would use the first. Regular Expressions can be brilliant, but they can also be unreliable if you define them incorrectly, or forget about a potential factor in the pattern.
$result = preg_replace ('/http:\/\/somesite\/(.+)\.png/', '[$1]', $text);
I'd use a # as regex delimiter.
$result = preg_replace('#http://somesite/(.+)\.png#', '[$1]', $text);
You can use this:
<?php
$text = 'check out this car http://somesite/ford.png'; //get submitted post
$link = strstr($text, 'http://'); //look for an http
$filename = pathinfo ($link, PATHINFO_FILENAME); //get filename from $link
$result = ereg_replace("http://([-]*[.]?[a-zA-Z0-9_/-?&%])*", "[$filename]", $text); // search on $text, find $link, replace it with $filename
echo $result;
?>
Output:
check out this car [ford]
Or if you wanna link to use forum
<?php
$text = 'check out this car http://somesite/ford.png'; //get submitted post
$link = strstr($text, 'http://'); //look for an http
$filename = pathinfo ($link, PATHINFO_FILENAME); //get filename from $link
$result = ereg_replace("http://([-]*[.]?[a-zA-Z0-9_/-?&%])*", "\\0", $text); // search on $text, find $link, replace it with $filename
echo $result;
?>
Or you want to up "ford" as link you can use this:
<?php
$text = 'check out this car http://somesite/ford.png'; //get submitted post
$link = strstr($text, 'http://'); //look for an http
$filename = pathinfo ($link, PATHINFO_FILENAME); //get filename from $link
$result = ereg_replace("http://([-]*[.]?[a-zA-Z0-9_/-?&%])*", "$filename", $text); // search on $text, find $link, replace it with $filename
echo $result;
?>
Related
How can I name a txt file after a site URL without the preceding https:// or http:// as in: www.google.com.txt?
I think I might be getting it wrong here: fopen($sitenameWithoutHTTP.".txt, "w");
Below is the way I'm trying to address that:
<?php
//
#mkdir("result", 0755);
#chdir("result");
$link = $sitename;
$sitename = preg_replace('#^https?://#', '', $sitenameWithoutHTTP);
$resultfile = fopen($sitenameWithoutHTTP.".txt", "w");
//
?>
Thanks for helping find a fix.
Hope this helps you achieve what you intended!
<?php
$siteName = 'https://www.google.com';
$siteNameWithoutHttps = preg_replace('#^https?://#', '', $siteName);
// print_r($siteNameWithoutHttps);
$resultFile = fopen($siteNameWithoutHttps.".txt", "w");
// run a check
if($resultFile == true) {
echo "success";
} else {
echo "failed";
}
The expected result for the commented print_r above should be:
www.google.com
$arr = ['http','https',':','/','?','&','#','.'];
$sitename = str_replace($arr, '', $sitenameWithoutHTTP);
also you can use base64_encode(), or use parse_url().
$HOST = parse_url($sitenameWithoutHTTP, PHP_URL_HOST);
and if you need to save real URL and get it again I see best way with using Md5 hash
$fileName = md5($sitenameWithoutHTTP).'.txt';
can get it again file.php/?getFile2url=[httpLink]
header('Location: '. Md5($_GET['getFile2url']).'.txt');
exit;
This question already has answers here:
Get Last Part of URL PHP
(14 answers)
Closed 7 years ago.
I need to remove every characters before the last "/"
This my url :
http://www.example.com/highlights/cat/all-about-clothing/
And I want to have only :
all-about-clothing
Thanks
Use basename()
$str = 'http://www.example.com/highlights/cat/all-about-clothing/';
echo basename($str);
// Outputs: all-about-clothing
EDIT:
Another Solution:
$str = 'http://www.example.com/highlights/cat/all-about-clothing/';
$path = pathinfo($str, PATHINFO_BASENAME);
echo "<br/>" . $path;
Use PHP's parse_url() function.
edit:
basename() or pathinfo() is the easier way.
$str = 'http://www.example.com/highlights/cat/all-about-clothing/';
$str = trim($str,'/');
$str = explode('/',$str);
echo $str = end($str);
// get result
all-about-clothing
<?php
$url = "http://www.example.com/highlights/cat/all-about-clothing/";
$url_path = parse_url($url, PHP_URL_PATH);
$basename = pathinfo($url_path, PATHINFO_BASENAME);
echo $basename;
?>
You can use regex too:
$match = [];
$subject = 'http://www.example.com/highlights/cat/all-about-clothing/';
$pattern = '/http:\/\/www\.example\.com\/highlights\/cat\/(.*)/';
preg_match($pattern, $subject, $match);
print_r($match);
You can see the result here.
<?php
$url = 'http://www.example.com/highlights/cat/all-about-clothing/';
$basename = split('/',$url);
echo $basename[5];
?>
Most of the above solution focus on the exact example URL,
Please be careful as if extra params are added to the end of the string,
you may get the wrong result:
http://www.example.com/highlights/cat/all-about-clothing/?page=1
http://www.example.com/highlights/cat/all-about-clothing/item/1
to cache the 3rd "directory" after the domain name, and ignore the rest of the URL, the following code can be used:
$url = "http://www.example.com/highlights/cat/all-about-clothing/item/1";
$url_path = parse_url($url, PHP_URL_PATH); # /highlights/cat/all-about-clothing/item/1
$dirs = explode('/', $url_path); # Array([0] =>"", [1]=>"highlights", [2]=>"cat", [3]=>"all-about-clothing", [4]=>"item", [5]=>"1")
echo $dirs[3]; # all-about-clothing
forexample, I have this url:
http://adstorage.jamba.net/storage/view/325/0/fa/Fairytale.mp3
How can I use PHP code so that it returns Fairytale. all the things before Fairytale and after that .mp3 should be removed.
the idetifier are / and .mp3 only the file name should be returned.
Use pathinfo() Function
<?php
$url = "http://example.com/file_name.mp3";
$f = pathinfo($url);
echo $f[filename]; // File name
?>
How about something like this:
$url = "http://adstorage.jamba.net/storage/view/325/0/fa/Fairytale.mp3";
$parts = parse_url($url);
$path_parts = explode('/', $parts['path']);
list($name, $extension) = explode(".", $path_parts[count($path_parts) - 1]);
echo $name;
This is probably overkill, and this thing could be done with a simple regex like:
preg_match("#.*/(\w+)\.\w+#", $url, $matches);
echo $matches[1];
Use pathinfo Function
<?php
$url = "http://adstorage.jamba.net/storage/view/325/0/fa/Fairytale.mp3";
$f = pathinfo($url);
echo $f[filename]; // File name Fairytale
print_r(pathinfo($url)); // File Array
?>
You can tryit with:
$input = 'http://adstorage.jamba.net/storage/view/325/0/fa/Fairytale.mp3';
echo current(explode('.', basename($input)));
Try in one line, $input being yout url (php 5.4) :
$name = explode('.',array_slice(explode('/',$input), -1, 1))[0];
I have:
$filename = basename(__FILE__);
$id = preg_replace("/\\.[^.\\s]{3,4}$/", "", $filename);
$id is filename without extension now. How can I remove not only extension but prefix and suffix from the file too?
prefix_ineedthis_suffix.php -> ineedthis
Update: Thanks for your answers! Unfortunately, I can mark only one answer as answer.
$prefix = 'prefix_';
$suffix = '_suffix';
$pattern = sprintf('/%s(.+)%s/i', $prefix, $suffix);
if (preg_match($pattern, $filename, $matches)) {
$id = $matches[1];
}
If "prefix" and "suffix" are parts separated by _ (underscore), then you might not need regex at all:
$parts = explode("_", $filename);
array_shift($parts);
array_pop($parts);
$ineedthis = implode("_", $parts);
OR, if ineedthis does not contain underscores for sure then:
$parts = explode("_", $filename);
$ineedthis = $parts[1];
If you still wanna use regex then:
if(preg_match("/^[^_]+_(.*)_[^_]+\.[a-z]{3,4}$/", $filename, $match))
$ineedthis = $match[1];
else
/// oops!
Use basename(string $path , string $suffix) instead. This can remove the directory part and also the extension part if you want.
$id = basename(__FILE__, "_suffix.php")
$prefix = "prefix_";
if (substr($id, 0, strlen($prefix) ) == $prefix) {
$id = substr($id, strlen($prefix), strlen($id) );
}
And according to this question this is faster than using RegEx.
You can use explode() twice to remove first the extension, then the prefix & suffix. This will store all the parts within arrays, which is handy if you later need those parts.
I am trying to create a simplified code to insert images dynamically into a page based on user entry similar to BBCode.
For example, if one of my users types "I like ducks [image]ducks[/image]", I want to explode the [image]ducks[/image], search MySQL for the keyword "ducks", pull the image path & name from the database that matches, then display the image HTML code as well as the source to the image.
function image_replace($dimg){
list($title) = explode("[image]",$dimg);
$query_image = mysql_query("SELECT * FROM images WHERE image_title LIKE '%$title%'");
$fetch_image = mysql_fetch_array($query_image);
$image_path = $fetch_image['image_path'];
$image_filename = $fetch_image['image_filename'];
$image_source = $image_path.$image_filename;
$dimg = str_replace("[image]","<img src=\"$image_source\">", $dimg);
$dimg = str_replace("[/image]","</img>", $dimg);
$dimg = str_replace("$title", "", $dimg);
return $img;
}
image_replace($ducks);
The wall I'm hitting is how to replace the text inside a dynamically generated page if it exists - and leave the content alone if the code doesn't exist. Any ideas?
EDIT - Complicating the problem:
Thanks for helping! I used your input to make the following function:
function image_replace($string){
$matches = array();
preg_match('/\[image\](.*)\[\/image\]/', $string, $matches);
$image = $matches[1];
$query_image = mysql_query("SELECT * FROM images WHERE image_title LIKE '%$image%'");
$fetch_image = mysql_fetch_array($query_image);
$image_path = $fetch_image['image_path'];
$image_filename = $fetch_image['image_filename'];
$image_source = $image_path.$image_filename;
$image_url = "<img src=\"$image_source\"></img>";
$new_string = preg_replace('/\[image\](.*)\[\/image\]/', $image_url, $string);
return $new_string;
}
I need this to work regardless of how many instances it occurs (thus if my user writes [image]duck[/image] then two sentences later writes [image]cow[/image], I want the function to replace both with their respective result). As it stands now, with more than one instance, it errors (not a valid SQL resource) which makes sense since preg_match only looks for one. I tried creating a loop (while & foreach w/ preg_match_all) to try testing the concept - both created infinite loops and my web server admin isn't too happy :p
I would try doing it with preg_match to get the image_url and preg_replace to replace it:
$string = 'I like ducks [image]ducks[/image]';
echo 'Before: ' . $string . '<br />';
$matches = array();
preg_match('/\[image\](.*)\[\/image\]/', $string, $matches);
$image = $matches[1];
//Lookup image_url and throw it in an <img>
$image_url = 'http://blah.com'; //Don't forget <img>
$new_string = preg_replace('/\[image\](.*)\[\/image\]/', $image_url, $string);
echo 'After: ' . $new_string;
edit
$string = "<br />I like ducks [image]ducks[/image]<br />I like cows [image]cows[/image]<br />I like pigs [image]pigs[/image]";
echo 'Before: ' . $string . '<br />';
$matches = array();
preg_match_all('/\[image\]([^\[]*)\[\/image\]/', $string, $matches);
$image_names = $matches[1];
foreach($image_names as $image_name) {
//Perform your lookup on each name
//If it is valid perform the replace
//Gonna say cows isn't there to test
if($image_name != 'cows') {
$image_url = 'http://blah.com'; //result of lookup
$string = preg_replace('/\[image\]' . $image_name . '\[\/image\]/', $image_url, $string);
}
}
echo 'After: ' . $string;