Simple templating with str_replace - php

I'm just experimenting first of all.
I just came up with an idea of making my own in a simple way here:
class Template
{
function parse($template_file, $braces)
{
if(file_exists($template_file))
{
$template = file_get_contents($template_file);
foreach($braces as $brace => $replacement)
{
$brace = trim(strtoupper($brace));
$build = str_replace('{' . $brace . '}', $replacement, $template);
}
echo $build;
}
else
{
trigger_error('Template file does not exist: ' . $template_file, E_ERROR);
}
}
}
This in order to work:
$template = new Template();
$template->parse('index_body.html', array('ONE' => 'one',
'TWO' => 'two',
'THREE' => 'three'));
index_body.html:
{ONE}
{TWO}
{THREE}
The problem is, that it only outputs:
{ONE} {TWO} three
It always replaces the last brace, how come not the whole array?

$build = str_replace('{' . $brace . '}', $replacement, $template);
^^^^^^^^^
You're always replacing against the original template, never against the updated one. Either keep assigning $template, or update $build

$template = file_get_contents($template_file);
$build = $template;
foreach($braces as $brace => $replacement)
{
$brace = trim(strtoupper($brace));
$build = str_replace('{' . $brace . '}', $replacement, $build);
}

It only replaces the last place because in each case, you're replacing the value in the original $template variable. It's not updating the variable each iteration.

You echo $build, which is being reassigned every foreach iteration.
You should've written this instead
$template = str_replace('{' . $brace . '}', $replacement, $template);

How about using like full php engine power (similar to smarty interface):
just for experimenting:
class Template {
private $_file;
private $_variables = array();
public function __construct($file = null) {
$this->_file = $file;
}
public function set($key, $value) {
$this->_variables[$key] = $value;
}
public function fetch($file = null) {
if (!$file) {
$file = $this->_file;
}
extract($this->_variables);
ob_start();
require($file);
$content = ob_get_contents();
ob_end_clean();
return $content;
}
public function display($file = null) {
if (!$file) {
$file = $this->_file;
}
$result = $this->fetch($file);
echo $result;
}
}
=============
$tpl = new Template('hello.tpl');
$tpl->set('world', 'earth');
$tpl->display();
=============
Template sample:hello.tpl
Hello <?=$world;?>

Your $build is overwritten in each iteration. This will solve the issue.
class Template
{
function parse($template_file, $braces)
{
if(file_exists($template_file))
{
$template = file_get_contents($template_file);
foreach($braces as $brace => $replacement)
{
$brace = trim(strtoupper($brace));
$temp = str_replace('{' . $brace . '}', $replacement, $template);//create a temporary array
$build = array_merge($build ,$temp);
}
echo $build;
}
else
{
trigger_error('Template file does not exist: ' . $template_file, E_ERROR);
}
}
}

Related

php shorten all urls with is.gd api in a string and linkify them

As the title says I'm trying to shorten all urls with is.gd api in a string and linkify them.
function link_isgd($text)
{
$regex = '#(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-~]*(\?\S+)?)?)?)#';
preg_match_all($regex, $text, $matches);
foreach($matches[0] as $longurl)
{
$tiny = file_get_contents('http://isnot.gd/api.php?longurl='.$longurl.'&format=json');
$json = json_decode($tiny, true);
foreach($json as $key => $value)
{
if ($key == 'errorcode')
{
$link = $longurl;
}
else if ($key == 'shorturl')
{
$link = $value;
}
}
}
return preg_replace($regex, ''.$link.'', $text);
}
$txt = 'Some text with links https://www.abcdefg.com/123 blah blah blah https://nooodle.com';
echo link_isgd($txt);
This is what I have got so far, linkifying works and so does shortening if only 1 url is in the string, however if theres 2 or more they all end up the same.
Note: the is.gd was not allowed in post, SO thought I was posting a short link which is not allowed here, so I had to change it to isnot.gd.
Your variable $link is not array so it takes only last assigned value of $link. You can replace preg_replace with str_replace and pass arrays with matches and links.
You can also use preg_replace_callback() and you can pass $matches directly to function which will replace with link. https://stackoverflow.com/a/9416265/7082164
function link_isgd($text)
{
$regex = '#(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-~]*(\?\S+)?)?)?)#';
preg_match_all($regex, $text, $matches);
$links = [];
foreach ($matches[0] as $longurl) {
$tiny = file_get_contents('http://isnot.gd/api.php?longurl=' . $longurl . '&format=json');
$json = json_decode($tiny, true);
foreach ($json as $key => $value) {
if ($key == 'errorcode') {
$links[] = $longurl;
} else if ($key == 'shorturl') {
$links[] = $value;
}
}
}
$links = array_map(function ($el) {
return '' . $el . '';
}, $links);
return str_replace($matches[0], $links, $text);
}

How to remove path after domain name from string

I have the following code :
function removeFilename($url)
{
$file_info = pathinfo($url);
return isset($file_info['extension'])
? str_replace($file_info['filename'] . "." . $file_info['extension'], "", $url)
: $url;
}
$url1 = "http://website.com/folder/filename.php";
$url2 = "http://website.com/folder/";
$url3 = "http://website.com/";
echo removeFilename($url1); //outputs http://website.com/folder/
echo removeFilename($url2);//outputs http://website.com/folder/
echo removeFilename($url3);//outputs http:///
Now my problem is that when there is only only a domain without folders or filenames my function removes website.com too.
My idea is there is any way on php to tell my function to do the work only after third slash or any other solutions you think useful.
UPDATED : ( working and tested )
<?php
function removeFilename($url)
{
$parse_file = parse_url($url);
$file_info = pathinfo($parse_file['path']);
return isset($file_info['extension'])
? str_replace($file_info['filename'] . "." . $file_info['extension'], "", $url)
: $url;
}
$url1 = "http://website.com/folder/filename.com";
$url2 = "http://website.org/folder/";
$url3 = "http://website.com/";
echo removeFilename($url1); echo '<br/>';
echo removeFilename($url2); echo '<br/>';
echo removeFilename($url3);
?>
Output:
http://website.com/folder/
http://website.org/folder/
http://website.com/
Sounds like you are wanting to replace a substring and not the whole thing. This function might help you:
http://php.net/manual/en/function.substr-replace.php
Since filename is at last slash you can use substr and str_replace to remove file name from path.
$PATH = "http://website.com/folder/filename.php";
$file = substr( strrchr( $PATH, "/" ), 1) ;
echo $dir = str_replace( $file, '', $PATH ) ;
OUTPUT
http://website.com/folder/
pathinfo cant recognize only domain and file name. But if without filename url is ended by slash
$a = array(
"http://website.com/folder/filename.php",
"http://website.com/folder/",
"http://website.com",
);
foreach ($a as $item) {
$item = explode('/', $item);
if (count($item) > 3)
$item[count($item)-1] ='';;
echo implode('/', $item) . "\n";
}
result
http://website.com/folder/
http://website.com/folder/
http://website.com
Close to the answer of splash58
function getPath($url) {
$item = explode('/', $url);
if (count($item) > 3) {
if (strpos($item[count($item) - 1], ".") === false) {
return $url;
}
$item[count($item)-1] ='';
return implode('/', $item);
}
return $url;
}

PHP preg_replace all occurrences for tags

I have this:
$tagName = "id";
$value = "ID12345";
$text = "<%id%> some text <%id%> something";
$a = new A();
echo $a->replaceAllTags($tagName, $value, $text);
and I want to create this:
"ID12345 some text ID12345 something"
Tried this and didn't work:
private function replaceAllTags($tagName, $value, $text)
{
$pattern = "/<%" . $tagName . "%>/";
while (preg_match($pattern, $text)) {
$text = preg_replace($pattern, $value, $text);
}
return $text;
}
This didn't work too:
private function replaceAllTags($tagName, $value, $text)
{
$pattern = "/<%(" . $tagName . ")%>/";
$text = preg_replace_callback($pattern,
function($m) {
return $value;
}, $text);
return $text;
}
EDITED:
Problem was that I wrote a PHPUnit test and had <%id> instead of <%id%>.
P.s.: private should be public
Besides the fact that a regex is not really needed for that, it seems to me the problem is with the "private" visibility. A method which you want to access from the outside needs the "public" visibility.
http://php.net/manual/en/language.oop5.visibility.php
Your method A::replaceAllTags declared as a private instead of public. Details here
If you want use regexp - try this snippet.
class A {
public function replaceAllTags($tagName, $value, $text) {
$pattern = "/<%(" . $tagName . ")%>/";
$text = preg_replace($pattern, $value, $text);
return $text;
}
}
I advise you to use simple str_replace. Like this:
public function replaceAllTags($tagName, $value, $text) {
$pattern = "<%" . $tagName . "%>";
$text = str_replace($pattern, $value, $text);
return $text;
}
this worked fine for me try it :
<?php
function replaceAllTags($tagName, $value, $text)
{
$pattern = "/(<%)(" . $tagName . ")(%>)/";
while (preg_match($pattern, $text)) {
$text = preg_replace($pattern, $value, $text);
}
return $text;
}
$tagName = "id";
$value = "ID12345";
$text = "<%id%> some text <%id%> something";
echo replaceAllTags($tagName, $value, $text);
?>
the result was : ID12345 some text ID12345 something
There is nothing wrong with any of the functions! Just keep in mind that your functions are private functions and can only be accessed withing that class!
You should use str_replace instead.
private function replaceAllTags($tagName, $value, $text)
{
$pattern = "<%" . $tagName . "%>";
$text = str_replace($pattern, $value, $text);
return $text;
}

How to add rel="nofollow" to links with preg_replace()

The function below is designed to apply rel="nofollow" attributes to all external links and no internal links unless the path matches a predefined root URL defined as $my_folder below.
So given the variables...
$my_folder = 'http://localhost/mytest/go/';
$blog_url = 'http://localhost/mytest';
And the content...
internal
internal cloaked link
external
The end result, after replacement should be...
internal
internal cloaked link
external
Notice that the first link is not altered, since its an internal link.
The link on the second line is also an internal link, but since it matches our $my_folder string, it gets the nofollow too.
The third link is the easiest, since it does not match the blog_url, its obviously an external link.
However, in the script below, ALL of my links are getting nofollow. How can I fix the script to do what I want?
function save_rseo_nofollow($content) {
$my_folder = $rseo['nofollow_folder'];
$blog_url = get_bloginfo('url');
preg_match_all('~<a.*>~isU',$content["post_content"],$matches);
for ( $i = 0; $i <= sizeof($matches[0]); $i++){
if ( !preg_match( '~nofollow~is',$matches[0][$i])
&& (preg_match('~' . $my_folder . '~', $matches[0][$i])
|| !preg_match( '~'.$blog_url.'~',$matches[0][$i]))){
$result = trim($matches[0][$i],">");
$result .= ' rel="nofollow">';
$content["post_content"] = str_replace($matches[0][$i], $result, $content["post_content"]);
}
}
return $content;
}
Here is the DOMDocument solution...
$str = 'internal
internal cloaked link
external
external
external
external
';
$dom = new DOMDocument();
$dom->preserveWhitespace = FALSE;
$dom->loadHTML($str);
$a = $dom->getElementsByTagName('a');
$host = strtok($_SERVER['HTTP_HOST'], ':');
foreach($a as $anchor) {
$href = $anchor->attributes->getNamedItem('href')->nodeValue;
if (preg_match('/^https?:\/\/' . preg_quote($host, '/') . '/', $href)) {
continue;
}
$noFollowRel = 'nofollow';
$oldRelAtt = $anchor->attributes->getNamedItem('rel');
if ($oldRelAtt == NULL) {
$newRel = $noFollowRel;
} else {
$oldRel = $oldRelAtt->nodeValue;
$oldRel = explode(' ', $oldRel);
if (in_array($noFollowRel, $oldRel)) {
continue;
}
$oldRel[] = $noFollowRel;
$newRel = implode($oldRel, ' ');
}
$newRelAtt = $dom->createAttribute('rel');
$noFollowNode = $dom->createTextNode($newRel);
$newRelAtt->appendChild($noFollowNode);
$anchor->appendChild($newRelAtt);
}
var_dump($dom->saveHTML());
Output
string(509) "<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
internal
internal cloaked link
external
external
external
external
</body></html>
"
Try to make it more readable first, and only afterwards make your if rules more complex:
function save_rseo_nofollow($content) {
$content["post_content"] =
preg_replace_callback('~<(a\s[^>]+)>~isU', "cb2", $content["post_content"]);
return $content;
}
function cb2($match) {
list($original, $tag) = $match; // regex match groups
$my_folder = "/hostgator"; // re-add quirky config here
$blog_url = "http://localhost/";
if (strpos($tag, "nofollow")) {
return $original;
}
elseif (strpos($tag, $blog_url) && (!$my_folder || !strpos($tag, $my_folder))) {
return $original;
}
else {
return "<$tag rel='nofollow'>";
}
}
Gives following output:
[post_content] =>
internal
<a href="http://localhost/mytest/go/hostgator" rel=nofollow>internal cloaked link</a>
<a href="http://cnn.com" rel=nofollow>external</a>
The problem in your original code might have been $rseo which wasn't declared anywhere.
Try this one (PHP 5.3+):
skip selected address
allow manually set rel parameter
and code:
function nofollow($html, $skip = null) {
return preg_replace_callback(
"#(<a[^>]+?)>#is", function ($mach) use ($skip) {
return (
!($skip && strpos($mach[1], $skip) !== false) &&
strpos($mach[1], 'rel=') === false
) ? $mach[1] . ' rel="nofollow">' : $mach[0];
},
$html
);
}
Examples:
echo nofollow('something');
// will be same because it's already contains rel parameter
echo nofollow('something'); // ad
// add rel="nofollow" parameter to anchor
echo nofollow('something', 'localhost');
// skip this link as internall link
Using regular expressions to do this job properly would be quite complicated. It would be easier to use an actual parser, such as the one from the DOM extension. DOM isn't very beginner-friendly, so what you can do is load the HTML with DOM then run the modifications with SimpleXML. They're backed by the same library, so it's easy to use one with the other.
Here's how it can look like:
$my_folder = 'http://localhost/mytest/go/';
$blog_url = 'http://localhost/mytest';
$html = '<html><body>
internal
internal cloaked link
external
</body></html>';
$dom = new DOMDocument;
$dom->loadHTML($html);
$sxe = simplexml_import_dom($dom);
// grab all <a> nodes with an href attribute
foreach ($sxe->xpath('//a[#href]') as $a)
{
if (substr($a['href'], 0, strlen($blog_url)) === $blog_url
&& substr($a['href'], 0, strlen($my_folder)) !== $my_folder)
{
// skip all links that start with the URL in $blog_url, as long as they
// don't start with the URL from $my_folder;
continue;
}
if (empty($a['rel']))
{
$a['rel'] = 'nofollow';
}
else
{
$a['rel'] .= ' nofollow';
}
}
$new_html = $dom->saveHTML();
echo $new_html;
As you can see, it's really short and simple. Depending on your needs, you may want to use preg_match() in place of the strpos() stuff, for example:
// change the regexp to your own rules, here we match everything under
// "http://localhost/mytest/" as long as it's not followed by "go"
if (preg_match('#^http://localhost/mytest/(?!go)#', $a['href']))
{
continue;
}
Note
I missed the last code block in the OP when I first read the question. The code I posted (and basically any solution based on DOM) is better suited at processing a whole page rather than a HTML block. Otherwise, DOM will attempt to "fix" your HTML and may add a <body> tag, a DOCTYPE, etc...
Thanks #alex for your nice solution. But, I was having a problem with Japanese text. I have fixed it as following way. Also, this code can skip multiple domains with the $whiteList array.
public function addRelNoFollow($html, $whiteList = [])
{
$dom = new \DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
$a = $dom->getElementsByTagName('a');
/** #var \DOMElement $anchor */
foreach ($a as $anchor) {
$href = $anchor->attributes->getNamedItem('href')->nodeValue;
$domain = parse_url($href, PHP_URL_HOST);
// Skip whiteList domains
if (in_array($domain, $whiteList, true)) {
continue;
}
// Check & get existing rel attribute values
$noFollow = 'nofollow';
$rel = $anchor->attributes->getNamedItem('rel');
if ($rel) {
$values = explode(' ', $rel->nodeValue);
if (in_array($noFollow, $values, true)) {
continue;
}
$values[] = $noFollow;
$newValue = implode($values, ' ');
} else {
$newValue = $noFollow;
}
// Create new rel attribute
$rel = $dom->createAttribute('rel');
$node = $dom->createTextNode($newValue);
$rel->appendChild($node);
$anchor->appendChild($rel);
}
// There is a problem with saveHTML() and saveXML(), both of them do not work correctly in Unix.
// They do not save UTF-8 characters correctly when used in Unix, but they work in Windows.
// So we need to do as follows. #see https://stackoverflow.com/a/20675396/1710782
return $dom->saveHTML($dom->documentElement);
}
<?
$str='internal
internal cloaked link
external';
function test($x){
if (preg_match('#localhost/mytest/(?!go/)#i',$x[0])>0) return $x[0];
return 'rel="nofollow" '.$x[0];
}
echo preg_replace_callback('/href=[\'"][^\'"]+/i', 'test', $str);
?>
Here is the another solution which has whitelist option and add tagret Blank attribute.
And also it check if there already a rel attribute before add a new one.
function Add_Nofollow_Attr($Content, $Whitelist = [], $Add_Target_Blank = true)
{
$Whitelist[] = $_SERVER['HTTP_HOST'];
foreach ($Whitelist as $Key => $Link)
{
$Host = preg_replace('#^https?://#', '', $Link);
$Host = "https?://". preg_quote($Host, '/');
$Whitelist[$Key] = $Host;
}
if(preg_match_all("/<a .*?>/", $Content, $matches, PREG_SET_ORDER))
{
foreach ($matches as $Anchor_Tag)
{
$IS_Rel_Exist = $IS_Follow_Exist = $IS_Target_Blank_Exist = $Is_Valid_Tag = false;
if(preg_match_all("/(\w+)\s*=\s*['|\"](.*?)['|\"]/",$Anchor_Tag[0],$All_matches2))
{
foreach ($All_matches2[1] as $Key => $Attr_Name)
{
if($Attr_Name == 'href')
{
$Is_Valid_Tag = true;
$Url = $All_matches2[2][$Key];
// bypass #.. or internal links like "/"
if(preg_match('/^\s*[#|\/].*/', $Url))
{
continue 2;
}
foreach ($Whitelist as $Link)
{
if (preg_match("#$Link#", $Url)) {
continue 3;
}
}
}
else if($Attr_Name == 'rel')
{
$IS_Rel_Exist = true;
$Rel = $All_matches2[2][$Key];
preg_match("/[n|d]ofollow/", $Rel, $match, PREG_OFFSET_CAPTURE);
if( count($match) > 0 )
{
$IS_Follow_Exist = true;
}
else
{
$New_Rel = 'rel="'. $Rel . ' nofollow"';
}
}
else if($Attr_Name == 'target')
{
$IS_Target_Blank_Exist = true;
}
}
}
$New_Anchor_Tag = $Anchor_Tag;
if(!$IS_Rel_Exist)
{
$New_Anchor_Tag = str_replace(">",' rel="nofollow">',$Anchor_Tag);
}
else if(!$IS_Follow_Exist)
{
$New_Anchor_Tag = preg_replace("/rel=[\"|'].*?[\"|']/",$New_Rel,$Anchor_Tag);
}
if($Add_Target_Blank && !$IS_Target_Blank_Exist)
{
$New_Anchor_Tag = str_replace(">",' target="_blank">',$New_Anchor_Tag);
}
$Content = str_replace($Anchor_Tag,$New_Anchor_Tag,$Content);
}
}
return $Content;
}
To use it:
$Page_Content = 'internal
internal
google
example
stackoverflow';
$Whitelist = ["http://yoursite.com","http://localhost"];
echo Add_Nofollow_Attr($Page_Content,$Whitelist,true);
WordPress decision:
function replace__method($match) {
list($original, $tag) = $match; // regex match groups
$my_folder = "/articles"; // re-add quirky config here
$blog_url = 'https://'.$_SERVER['SERVER_NAME'];
if (strpos($tag, "nofollow")) {
return $original;
}
elseif (strpos($tag, $blog_url) && (!$my_folder || !strpos($tag, $my_folder))) {
return $original;
}
else {
return "<$tag rel='nofollow'>";
}
}
add_filter( 'the_content', 'add_nofollow_to_external_links', 1 );
function add_nofollow_to_external_links( $content ) {
$content = preg_replace_callback('~<(a\s[^>]+)>~isU', "replace__method", $content);
return $content;
}
a good script which allows to add nofollow automatically and to keep the other attributes
function nofollow(string $html, string $baseUrl = null) {
return preg_replace_callback(
'#<a([^>]*)>(.+)</a>#isU', function ($mach) use ($baseUrl) {
list ($a, $attr, $text) = $mach;
if (preg_match('#href=["\']([^"\']*)["\']#', $attr, $url)) {
$url = $url[1];
if (is_null($baseUrl) || !str_starts_with($url, $baseUrl)) {
if (preg_match('#rel=["\']([^"\']*)["\']#', $attr, $rel)) {
$relAttr = $rel[0];
$rel = $rel[1];
}
$rel = 'rel="' . ($rel ? (strpos($rel, 'nofollow') ? $rel : $rel . ' nofollow') : 'nofollow') . '"';
$attr = isset($relAttr) ? str_replace($relAttr, $rel, $attr) : $attr . ' ' . $rel;
$a = '<a ' . $attr . '>' . $text . '</a>';
}
}
return $a;
},
$html
);
}

replace string with PHP code

I need to find a string within a string ("foo", for example) and then replace it with a PHP code. Is it possible?
I'm creating a Joomla Plugin. When my article has something like "{foo}", i will replace it with an include (require, or whatever).
I've made something like:
public function onContentBeforeDisplay($context, &$row, &$params, $page=0)
{
// $row->text has the article text ...
if (preg_match('/{contact-form}/', $row->text))
{
require_once(dirname(__FILE__) . DS . 'tmpl' . DS . 'default.php');
}
}
But this code will insert default.php at the beginning. I want to replace it in {contact-form} tag.
Thank you.
You can use the PHP function "substr_replace()", whose details are given here.
\n";
/* These two examples replace all of $var with 'bob'. */
echo substr_replace($var, 'bob', 0) . "<br />\n";
echo substr_replace($var, 'bob', 0, strlen($var)) . "<br />\n";
/* Insert 'bob' right at the beginning of $var. */
echo substr_replace($var, 'bob', 0, 0) . "<br />\n";
/**
* Your food & search is here
*/
/* These next two replace 'MNRPQR' in $var with 'bob'. */
echo substr_replace($var, 'bob', 10, -1) . "<br />\n";
echo substr_replace($var, 'bob', -7, -1) . "<br />\n";
/* Delete 'MNRPQR' from $var. */
echo substr_replace($var, '', 10, -1) . "<br />\n";
?>
You can create a PHP file that matches the keyword (like: foo.php) and simply extract the keyword from the text and use it to include that file.
For example:
<?php
$str = "This is {foo} text";
$includePath = "/path/to/my/files/";
// Careful with the Regular Expression. If you allow chars like . in the
// keyword this could create a security problem. (Dots allow you to go backwards
// which would allow people to execute files outside your path.)
if (preg_match_all('/\{([\w]+)\}/', $str, $matches))
{
foreach ($matches[1] as $_match)
{
$filePath = $includePath . $_match . ".php";
if (file_exists($filePath))
{
include $filePath;
}
else
{
trigger_error("File does not exist '$filePath'.", E_USER_WARNING);
}
}
}
?>
I think you just want this, don't you?
<?php
$replacement = file_get_contents('myfile.php');
$content = str_replace('{foo}', eval($replacement), $content);
?>
If you need to replace any string on series of files on your remote server and well you don't have time for it! , here is your solution , I hope it can help someone.
////
//PHP 5.3 + Class find and replace string in files
//
//by Bruce Afruz
//
//2013
//
//example usage for single file:
//
//$new = new fileReplacement('./');
//$new->setExt("check.php");
//$new->changeContents("hello", "goodbye");
//
//example usage for multiple files:
//
//$new = new fileReplacement('./test');
//$new->setExt("*.html");
//$new->changeContents("hello", "goodbye");
//
//to change directory:
//
//$new = new fileReplacement('./test');
//$new->setDir("./test2");
//$new->setExt("*.html");
//$new->changeContents("hello", "goodbye");
////
class fileReplacement
{
private $ext , $dir ;
public function getDir() {
return $this->dir;
}
public function setDir($dir) {
$this->dir = $dir;
}
public function getExt() {
return $this->ext;
}
public function setExt($ext) {
$this->ext = $ext;
}
function __construct($dir) {
$this->dir = $dir;
}
public function rglob($pattern = '*', $flags = 0, $path = '') {
chdir($this->getDir());
$paths = glob($path . '*', GLOB_MARK | GLOB_ONLYDIR | GLOB_NOSORT);
$files = glob($path . $pattern, $flags);
foreach ($paths as $path) {
$files = array_merge($files, $this->rglob($pattern, $flags, $path));
}
return $files;
}
public function changeContents($replace , $sentence , $flags = 0, $path = '') {
$all = $this->rglob($this->getExt() , $flags, $path);
foreach ($all as $file) {
$filename = $file;
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
$contents = str_replace($replace , $sentence, $contents);
if (is_writable($filename)) {
if (!$handle = fopen($filename, 'w+')) {
echo "Cannot open file ($filename)
";
exit;
}
// Write $contents to our opened file.
if (fwrite($handle, $contents) === FALSE) {
echo "Cannot write to file ($filename)
";
exit;
}
echo "Success, wrote content to file ($filename)
";
fclose($handle);
} else {
echo "The file $filename is not writable
";
}
}
}}

Categories