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;
Related
[amount] = "58"
I have a large text file, and am trying to find where amount occurs and print the 58, as I am scraping HTML on multiple pages, all with similar layouts, but the amount value changes on each page. The only constant is that the string [amount] occurs once, so I am able to use it to find the number value.
I would like to know how to do this in PHP.
Thanks.
The code I tried with was
$filename = 'site.txt';
$searchfor = '[amount]';
$file = file_get_contents($filename);
if(strpos($file, $searchfor [$offset = 6]))
{
echo $searchfor;
}
I guess you want to find the number 58, this can be done e.g.
input was site.txt:
some text [amount] = "58" some other text
running on cli: php test.php:
<?php
$filename = './site.txt';
$searchfor = '[amount]';
$file = file_get_contents($filename);
foreach( explode("\n", $file) as $line ){
$found = strpos($line, $searchfor);
if($found){
echo "string found on position: ".$found." in '" . $line. "'\n";
echo "so the searched stuff should be: '" . explode('"', substr($line,$found,strlen($line)-$found))[1] ."'\n";
}
}
?>
results in output:
string found on position: 10 in 'some text [amount] = "58" some other text'
so the searched stuff should be: '58'
$filename = 'site.txt';
$searchfor = '[amount] = "';
$file = file_get_contents($filename);
//find the position
$pos = strpos($file, $searchfor);
//check for real false here
if($pos!==false) {
//print from the found postion+lengthofserachfor
//(int) makes an real number if you get '6 abc' an real 6
echo (int)substr($file,$pos+strlen($searchfor),5);
}
So far, done.
if(preg_match('#amount\][ ]?=[ ]?"([0-9]+)#',$file,$matches)){
print_r($matches);
}
Have a nice day.
I have been struggling with this now for 2 hours and it's driving me nuts. And I don't think it is likely hard. I am using Wordpress and need to replace the IMG urls from an old path to a new path. Problem is..everything about the url is static except a particular directory which is random.
Example:
https://cdn2.content.mysite.com/uploads/user/76eb326b-62ff-4d37-bf4b-01a428e2f9f6/0ffd6c15-8a13-437c-9661-36edfe11cb41/Image/b1493cd89a29c0a2d1d8e0939f05d8ee/booth_w640.jpeg
should become
/wp-content/uploads/imports/booth_w640.jpeg
The bold part is random. So I have this in my wordpress functions.php
function replace_content($content) {
$reg = '#/https://cdn2.content.mysite.com/uploads/user/76eb326b-62ff-4d37-bf4b-01a428e2f9f6/0ffd6c15-8a13-437c-9661-36edfe11cb41/Image/([^/]+)#i';
$rep = '/wp-content/uploads/imports';
$content = preg_replace($reg, $rep ,$content);
return $content;
}
add_filter('the_content','replace_content');
but that isn't working. I can't figure it out. Any help?
I think what you need is:
function replace_content($content) {
$reg = '#/static-part-of-url/([^/]+)#i';
$rep = '/wp-content/uploads/imports';
$content = preg_replace($reg, $rep ,$content);
return $content;
}
add_filter('the_content','replace_content');
Using a different delimiter than / is better when trying to match URLs.
Here is the script in action.
I determined the answer to my problem using the below code
preg_match( '/src="([^"]*)"/i', $content, $match ) ;
$getURL = $match[1];
$urlArr = explode("/",$getURL);
$fileName = end($urlArr);
$newURL = "/blog/wp-content/uploads/imports/" . $fileName;
$content = str_replace($getURL, $newURL, $content);
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;
?>
I'm running into an issue with finding specific text and replacing it with alternative text.
I'm testing my code below with .rtf and .txt files only. I'm also ensuring the files are writable, from within my server.
It's a hit and miss situation, and I'm curious if my code is wrong, or if this is just weirdness of opening and manipulating files.
<?php
$filelocation = '/tmp/demo.txt';
$firstname = 'John';
$lastname = 'Smith';
$output = file_get_contents($filelocation);
$output = str_replace('[[FIRSTNAME]]', $firstname, $output);
$output = str_replace('[[LASTNAME]]', $lastname, $output);
$output = str_replace('[[TODAY]]', date('F j, Y'), $output);
// rewrite file
file_put_contents($filelocation, $output);
?>
So, inside the demo.txt file I have about a full page of text with [[FIRSTNAME]], [[LASTNAME]], and [[TODAY]] scattered around.
It's hit and miss with the find/replace. So far, [[TODAY]] is always replaced correctly, while the names aren't.
Has anyone had this same issue?
(on a side note, I've checked error logs and so far no PHP warning/error is returned from opening the file, nor writing it)
Hard to say for sure without seeing the contents of demo.txt. My first guess is that it might be a problem with using brackets for your pointers. I would try changing to something not used by RTF like percent signs or an asterisk. ex: %%FIRSTNAME%%, **FIRSTNAME** (this is assuming of course that you have control of the contents of demo.txt.)
I have had this issue too. It seems like Microsoft Word inserts formatting codes in the tags. I have made a blog post about how to get around this on my technical blog.
http://tech.humlesite.eu/2017/01/13/using-regular-expression-to-merge-database-content-into-rich-text-format-template-documents/
The PHP example is shown here:
<?php
$file = file_get_contents('mergedoc.rtf');
// To temporary get rid of the escape characters...
$mergetext = str_replace("\\", "€€", $file);
// New seven part regex with default value detection
$regex2 = '/<<((?:€€[a-z0-9]*|\}|\{|\s)*)([a-z0-9.\-\+_æøåÆØÅA-Z]*)((?:€€[a-z0-9]*|\}|\{|\s)*)([a-z0-9.\-\+_æøåÆØÅA-Z]*)((?:€€[a-z0-9]*|\}|\{|\s)*)(?:\s*:(.*?)\s*)?((?:€€[a-z0-9]*|\}|\{|\s)*)>>/';
// Find all the matches in it....
preg_match_all($regex2,$mergetext, $out, PREG_SET_ORDER);
// Lets see the result
var_dump($out);
foreach ($out as $match) {
$whole_tag = $match[0]; // The part we actually replace.
$start = $match[1]; // The start formatting that has been injected in our tag, if any
$tag = $match[2]; // The tag word itself.
if (($match[4].$match[6]) != "") { //some sec-part tag or default value?
$end = $match[5]; // The end formatting that might be inserted.
if ($end == "") {
$end = $match[7]; // No end in 5, we try 7.
}
} else {
$end = $match[3]; // No second tag or default value, we find end in match-3
}
$secPartTag = $match[4]; // Do we have inserted some formatting inside the tag word too ?
if ($secPartTag != "") {
$tag .= $secPartTag; // Put it together with the tag word.
}
$default_value = $match[6];
// Simple selection of what we do with the tag.
switch ($tag) {
case 'COMPANY_NAME':
$txt = "MY MERGE COMPANY EXAMPLE LTD";
break;
case 'SOMEOTHERTAG':
$txt = "SOME OTHER TEXT XX";
break;
case 'THISHASDEFAULT':
$txt = "";
break;
default:
$txt = "NOTAG";
}
if ($txt == "") {
$txt = $default_value;
}
// Create RTF Line breaks in text, if any.
$txt = str_replace(chr(10), chr(10)."\\line", $txt);
// Do the replace in the file.
$mergetext = str_replace($whole_tag, $start.$txt.$end, $mergetext);
}
// Put back the escape characters.
$file = str_replace("€€", "\\", $mergetext);
// Save to file. Extention .doc makes it open in Word by default.
file_put_contents("ResultDoc.doc", $file);
?>
Hi I've got these lines here, I am trying to extract the first paragraph found in the file, but this fails to return any results, if not it returns results that are not even in <p> tags which is odd?
$file = $_SERVER['DOCUMENT_ROOT'].$_SERVER['REQUEST_URI'];
$hd = fopen($file,'r');
$cn = fread($hd, filesize($file));
fclose($hd);
$cnc = preg_replace('/<p>(.+?)<\/p>/','$1',$cn);
Try this:
$html = file_get_contents("http://localhost/foo.php");
preg_match('/<p>(.*)<\/p>/', $html, $match);
echo($match[1]);
I would use DOM parsing for that:
// SimpleHtmlDom example
// Create DOM from URL or file
$html = file_get_html('http://localhost/blah.php');
// Find all paragraphs
foreach($html->find('p') as $element)
echo $element->innerText() . '<br>';
It would allow you to more reliably replace some of the markup:
$html->find('p', 0)->innertext() = 'foo';