how to put array bad words in file .txt php - php

i am trying to use this code to filter bad word and it work good but i want to put the bad words in .txt file i try different ways but did not work
$GLOBALS['bad_words']= array('truck' => true, 'shot' => true);
function containsBadWord($str){
$str= trim($str);
$str= preg_replace('/\s+/', ' ', $str);
$word_list= explode(" ", $str);
foreach($word_list as $word){
if( isset($GLOBALS['bad_words'][$word]) ){
return true;
}
}
return false;
}

To write bad words into a file, you can use file_put_contents() and store it in JSON using json_encode().
<?php
$GLOBALS['bad_words']= array('truck' => true, 'shot' => true);
file_put_contents('/path/to/bad_word.txt',json_encode($GLOBALS['bad_words']));
#Update:
To get bad words from this file, you can use file_get_contents() and json_decode().
$bad_words = json_decode(file_get_contents('/path/to/bad_word.txt'),true);
$GLOBALS['bad_words'] = $bad_words;

Related

How to read a csv file with php code inside?

i searched Google but found nothing what fits for my problem, or i search with the wrong words.
In many threads i read, the smarty Template was the solution, but i dont wont use smarty because its to big for this little project.
My problem:
I got a CSV file, this file contents only HTML and PHP code, its a simple html template document the phpcode i use for generating dynamic imagelinks for example.
I want to read in this file (that works) but how can i handle the phpcode inside this file, because the phpcode shown up as they are. All variables i use in the CSV file still works and right.
Short Version
how to handle, print or echo phpcode in a CSV file.
thanks a lot,
and sorry for my Bad english
Formatting your comment above you have the following code:
$userdatei = fopen("selltemplate/template.txt","r");
while(!feof($userdatei)) {
$zeile = fgets($userdatei);
echo $zeile;
}
fclose($userdatei);
// so i read in the csv file and the content of csv file one line:
// src="<?php echo $bild1; ?>" ></a>
This is assuming $bild1 is defined somewhere else, but try using these functions in your while loop to parse and output your html/php:
$userdatei = fopen("selltemplate/template.txt","r");
while(!feof($userdatei)) {
$zeile = fgets($userdatei);
outputResults($zeile);
}
fclose($userdatei);
//-- $delims contains the delimiters for your $string. For example, you could use <?php and ?> instead of <?php and ?>
function parseString($string, $delims) {
$result = array();
//-- init delimiter vars
if (empty($delims)) {
$delims = array('<?php', '?>');
}
$start = $delims[0];
$end = $delims[1];
//-- where our delimiters start/end
$php_start = strpos($string, $start);
$php_end = strpos($string, $end) + strlen($end);
//-- where our php CODE starts/ends
$php_code_start = $php_start + strlen($start);
$php_code_end = strpos($string, $end);
//-- the non-php content before/after the php delimiters
$pre = substr($string, 0, $php_start);
$post = substr($string, $php_end);
$code_end = $php_code_end - $php_code_start;
$code = substr($string, $php_code_start, $code_end);
$result['pre'] = $pre;
$result['post'] = $post;
$result['code'] = $code;
return $result;
}
function outputResults($string) {
$result = parseString($string);
print $result['pre'];
eval($result['code']);
print $result['post'];
}
Having PHP code inside a CSV file that should be parsed and probably executed using eval sounds pretty dangerous to me.
If I get you right you just want to have dynamic parameters in your CSV file right? If thats the case and you don't want to implement an entire templating language ( like Mustache, Twig or Smarty ) into your application you could do a simple search and replace thing.
$string = "<img alt='{{myImageAlt}}' src='{{myImage}}' />";
$parameters = [
'myImageAlt' => 'company logo',
'myImage' => 'assets/images/logo.png'
];
foreach( $parameters as $key => $value )
{
$string = str_replace( '{{'.$key.'}}', $value, $string );
}

How to get preg_replace() to delete text between two tags?

I'm trying to make a function in PHP that can delete code within two tags from all .js file within one folder and all its subfolders. So far everything works except preg_replace(). This is my code:
<?php
deleteRealtimeTester('test');
function deleteRealtimeTester($folder_path)
{
foreach (glob($folder_path . '/*.js') as $file)
{
$string = file_get_contents($file);
$string = preg_replace('#//RealtimeTesterStart(.*?)//RealtimeTesterEnd#', 'test2', $string);
$file_open = fopen($file, 'wb');
fwrite($file_open, $string);
fclose($file_open);
}
$subfolders = array_filter(glob($folder_path . '/*'), 'is_dir');
if (sizeof($subfolders) > 0)
{
for ($i = 0; $i < sizeof($subfolders); $i++)
{
echo $subfolders[$i];
deleteRealtimeTester($subfolders[$i]);
}
}
else
{
return;
}
}
?>
As mentioned I want to delete everything inside these tags and the tags themselve:
//RealtimeTesterStart
//RealtimeTesterEnd
It is important that the tags contains the forward slashes and also that if a file contains multiple of these tags, only code from //RealtimeTesterStart to //RealtimeTesterEnd is deleted and not from //RealtimeTesterEnd to //RealtimeTesterStart.
I hope that someone can help me.
You could also change your regex to use the [\s\S] character set which can be used to match any character, including line breaks.
So have the following
preg_replace('#\/\/RealtimeTesterStart[\s\S]+\/\/RealtimeTesterEnd#', '', $string);
This would remove the contents of //RealtimeTesterStart to //RealtimeTesterEnd and the tags themselves.
I'm assuming that //RealtimeTesterStart, //RealtimeTesterEnd and the code in between are on different lines? In PCRE . does NOT match newlines. You need to use the s modifier ( and you don't need the () unless you need the captured text for the replacement):
#//RealtimeTesterStart.*?//RealtimeTesterEnd#s
Also, look at GLOB_ONLYDIR for glob instead of array_filter. Also, also, maybe file_put_contents instead of fopen etc.
Maybe something like:
foreach (glob($folder_path . '/*.js') as $file) {
$string = file_get_contents($file);
$string = preg_replace('#//RealtimeTesterStart.*?//RealtimeTesterEnd#s', 'test2', $string);
file_put_contents($file, $string);
}
foreach(glob($folder_path . '/*', GLOB_ONLYDIR) as $subfolder) {
deleteRealtimeTester($subfolder);
}

Run a variable through several functions

I am attempting to run a variable through several functions to obtain a desired outcome.
For example, the function to slugify a text works like this:
// replace non letter or digits by -
$text = preg_replace('~[^\\pL\d]+~u', '-', $text);
// trim
$text = trim($text, '-');
// transliterate
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
// lowercase
$text = strtolower($text);
// remove unwanted characters
$text = preg_replace('~[^-\w]+~', '', $text);
However, we can see that there is a pattern in this example. The $text variable is passed through 5 function calls like this: preg_replace(..., $text) -> trim($text, ...) -> iconv(..., $text) -> strtolower($text) -> preg_replace(..., $text).
Is there a better way we can write the code to allow a variable sieve through several functions?
One way is to write the above code like this:
$text = preg_replace('~[^-\w]+~', '', strtolower(iconv('utf-8', 'us-ascii//TRANSLIT', trim(preg_replace('~[^\\pL\d]+~u', '-', $text), '-'))));
... but this way of writing is a joke and mockery. It hinders code readability.
Since your "function pipeline" is fixed then this is the best (and not coincidentally simplest) way.
If the pipeline were to be dynamically constructed then you could do something like:
// construct the pipeline
$valuePlaceholder = new stdClass;
$pipeline = array(
// each stage of the pipeline is described by an array
// where the first element is a callable and the second an array
// of arguments to pass to that callable
array('preg_replace', array('~[^\\pL\d]+~u', '-', $valuePlaceholder)),
array('trim', array($valuePlaceholder, '-')),
array('iconv', array('utf-8', 'us-ascii//TRANSLIT', $valuePlaceholder)),
// etc etc
);
// process it
$value = $text;
foreach ($pipeline as $stage) {
list($callable, $parameters) = $stage;
foreach ($parameters as &$parameter) {
if ($parameter === $valuePlaceholder) {
$parameter = $value;
}
}
$value = call_user_func_array($callable, $parameters);
}
// final result
echo $value;
See it in action.
use this as a combination of all five
$text = preg_replace('~[^-\w]+~', '', strtolower(iconv('utf-8', 'us-ascii//TRANSLIT', trim(preg_replace('~[^\\pL\d]+~u', '-', $text), '-'))));
but use as you are trying.because it is good practice rather than writing in one line.

function to name an image file for using in a url

Im creating a Yii app where i will save images into the database. Now im searching a php or yii function that make this image file name clean so i can use later in my urls.
For example if i upload:
test image.jpg
testímage.jpg
tést ímage.jpg
in my database i can save them as test-image.jpg or just testimage.jpg
Which other methods do you use? You use real names or just time stamps ? Which you think is the method to go to avoid duplicates?
Thanks
Personally I would keep the original filename. If you need something unique, you could add a hash or the id of the row at the end. I know that's just for the last 10% percent maybe, but if the filename represents what's shown in the picture, you can gain in SEO.
To make your filename "clean", you can use functions like this (PHP):
function trim($value, $onlySingleSpaces = false, $to1Line = false) {
$value = trim($value);
// change new lines and tabs to single spaces
if ($to1Line !== false)
$value = str_replace(array("\r\n", "\r", "\n", "\t"), ' ', $value);
// multispaces to single whitespaces
if ($onlySingleSpaces !== false)
$value = ereg_replace(" {2,}", ' ',$value);
return $value;
}
function removeAccent($value) {
$a = array('À','Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô','Õ','Ö','Ø','Ù','Ú','Û','Ü','Ý','ß','à','á','â','ã','ä','å','æ','ç','è','é','ê','ë','ì','í','î','ï','ñ','ò','ó','ô','õ','ö','ø','ù','ú','û','ü','ý','ÿ','Ā','ā','Ă','ă','Ą','ą','Ć','ć','Ĉ','ĉ','Ċ','ċ','Č','č','Ď','ď','Đ','đ','Ē','ē','Ĕ','ĕ','Ė','ė','Ę','ę','Ě','ě','Ĝ','ĝ','Ğ','ğ','Ġ','ġ','Ģ','ģ','Ĥ','ĥ','Ħ','ħ','Ĩ','ĩ','Ī','ī','Ĭ','ĭ','Į','į','İ','ı','IJ','ij','Ĵ','ĵ','Ķ','ķ','Ĺ','ĺ','Ļ','ļ','Ľ','ľ','Ŀ','ŀ','Ł','ł','Ń','ń','Ņ','ņ','Ň','ň','ʼn','Ō','ō','Ŏ','ŏ','Ő','ő','Œ','œ','Ŕ','ŕ','Ŗ','ŗ','Ř','ř','Ś','ś','Ŝ','ŝ','Ş','ş','Š','š','Ţ','ţ','Ť','ť','Ŧ','ŧ','Ũ','ũ','Ū','ū','Ŭ','ŭ','Ů','ů','Ű','ű','Ų','ų','Ŵ','ŵ','Ŷ','ŷ','Ÿ','Ź','ź','Ż','ż','Ž','ž','ſ','ƒ','Ơ','ơ','Ư','ư','Ǎ','ǎ','Ǐ','ǐ','Ǒ','ǒ','Ǔ','ǔ','Ǖ','ǖ','Ǘ','ǘ','Ǚ','ǚ','Ǜ','ǜ','Ǻ','ǻ','Ǽ','ǽ','Ǿ','ǿ');
$b = array('A','A','A','A','AE','A','AE','C','E','E','E','E','I','I','I','I','D','N','O','O','O','O','OE','O','U','U','U','UE','Y','ss','a','a','a','a','ae','a','ae','c','e','e','e','e','i','i','i','i','n','o','o','o','o','oe','o','u','u','u','ue','y','y','A','a','A','a','A','a','C','c','C','c','C','c','C','c','D','d','D','d','E','e','E','e','E','e','E','e','E','e','G','g','G','g','G','g','G','g','H','h','H','h','I','i','I','i','I','i','I','i','I','i','IJ','ij','J','j','K','k','L','l','L','l','L','l','L','l','l','l','N','n','N','n','N','n','n','O','o','O','o','O','o','OE','oe','R','r','R','r','R','r','S','s','S','s','S','s','S','s','T','t','T','t','T','t','U','u','U','u','U','u','U','u','U','u','U','u','W','w','Y','y','Y','Z','z','Z','z','Z','z','s','f','O','o','U','u','A','a','I','i','O','o','U','u','U','u','U','u','U','u','U','u','A','a','AE','ae','O','o');
return str_replace($a, $b, $value);
}
// trims, removes whitespaces, double "-", accents and stuff … :)
function clean($value) {
return ereg_replace("-{2,}", '-', ereg_replace("_{1,}", '-', preg_replace( array('/[^a-zA-Z0-9 -_]/', '/[&]+/', '/[ ]+/', '/^-|-$/'), array('', '', '-', ''), removeAccent( trim($value, true, true) ) ) ) );
}

string replace in a file with php

I am writing an email module for my web app that sends a html email to a user on completion of a task such as signing up. Now as the formatting of this email may change I've decided to have a template html page that is the email, with custom tags in it that need to be replaced such as %fullname%.
My function has an array in the format of array(%fullname% => 'Joe Bloggs'); with the key as the tag identifier and the value of what needs to replace it.
I've tried the following:
$fp = #fopen('email.html', 'r');
if($fp)
{
while(!feof($fp)){
$line = fgets($fp);
foreach($data as $value){
echo $value;
$repstr = str_replace(key($data), $value, $line);
}
$content .= $repstr;
}
fclose($fp);
}
Is this the best way to do this? as only 1 tag get replaced at the moment... am I on the right path or miles off??
thanks...
I think the problem is in your foreach. This should fix it:
foreach($data as $key => $value){
$repstr = str_replace($key, $value, $line);
}
Alternatively, I think this should be more effective:
$file = #file_get_contents("email.html");
if($file) {
$file = str_replace(array_keys($data), array_values($data), $file);
print $file;
}
//read the entire string
$str=implode("\n",file('somefile.txt'));
$fp=fopen('somefile.txt','w');
//replace something in the file string - this is a VERY simple example
$str=str_replace('Yankees','Cardinals',$str);
//now, TOTALLY rewrite the file
fwrite($fp,$str,strlen($str));
That looks like it should work, but I'd use "file_get_contents()" and do it in one big blast.
A slightly different approach is to use PHP's heredocs combined with string interpolation i.e.:
$email = <<<EOD
<HTML><BODY>
Hi $fullname,
You have just signed up.
</BODY></HTML>
EOD;
This avoids a separate file, and should make things beyond simple substitution easier later.

Categories