بسم الله الرحمن الرحیم

نکات پی اچ پی-php

فهرست علوم
علوم کامپیوتر
نکات پی اچ پی-php
وارد کردن متن در وسط فایل با پی اچ پی-php



برای دیدن کدها به سورس ماجعه کنید





header('Content-Type: text/html; charset=utf-8', true); $string = 'الْحَمْدُ لِلَّهِ رَبِّ الْعَالَمِينَ';
$remove = array('ِ', 'ُ', 'ٓ', 'ٰ', 'ْ', 'ٌ', 'ٍ', 'ً', 'ّ', 'َ'); $string = str_replace($remove, '', $string);
echo $string; // outputs الحمد لله رب العالمين

$string = 'الْحَمْدُ لِلَّهِ رَبِّ الْعَالَمِينَ'; $string = preg_replace("~[\x{064B}-\x{065B}]~u", "", $string); echo $string; // outputs الحمد لله رب العالمين


Try this code, it's works fine:
$unicode = [ "~[\x{0600}-\x{061F}]~u", "~[\x{063B}-\x{063F}]~u", "~[\x{064B}-\x{065E}]~u", "~[\x{066A}-\x{06FF}]~u", ];
$str = preg_replace($unicode, "", $str);


", $path_to_file, "
"; $find = strip_tags($find); //$find = str_replace($remove, '', $find); $find = str_replace($name, "$name", $find); echo $find, "
"; $count++; echo $count, "

"; } } } } ?>


I had the same problem , I edit the /etc/apache2/apache2.conffile and add
Order allow,deny Allow from all Require all granted
and reset the apache2
sudo service apache2 restart
work for me .


while(! feof($file)) { echo fgets($file). "
"; }
fclose($file); ?>
The readfile() function reads a file and writes it to the output buffer.
And a PHP example, multiple matching lines will be displayed:
// the following line prevents the browser from parsing this as HTML. header('Content-Type: text/plain');
// get the file contents, assuming the file to be readable (and exist) $contents = file_get_contents($file); // escape special characters in the query $pattern = preg_quote($searchfor, '/'); // finalise the regular expression, matching the whole line $pattern = "/^.*$pattern.*\$/m"; // search, and store all matching occurences in $matches if(preg_match_all($pattern, $contents, $matches)){ echo "Found matches:\n"; echo implode("\n", $matches[0]); } else{ echo "No matches found"; }

The file() reads a file into an array.
Each array element contains a line from the file, with the newline character still attached.

Just read the whole file as array of lines using file function.
function getLineWithString($fileName, $str) { $lines = file($fileName); foreach ($lines as $lineNumber => $line) { if (strpos($line, $str) !== false) { return $line; } } return -1; }
If you use file rather than file_get_contents you can loop through an array line by line searching for the text and then return that element of the array.
martijn at martijnfrazer dot nl ¶ 8 years ago This is a function I wrote to find all occurrences of a string, using strpos recursively.

This is how you use it:
if($found) { foreach($found as $pos) { echo 'Found "'.$search.'" in string "'.$string.'" at position '.$pos.'
'; } } else { echo '"'.$search.'" not found in "'.$string.'"'; } ?>

saving it as mytextfile.txt
Now just make a PHP file to read the text of a particular line

Output:
hello again I am from line no 3



$wordsAry[$i]"; $text = str_ireplace($wordsAry[$i], $highlighted_text, $text); }
return $text; } ?>


$keyword = "fun"; $look = explode(' ',$str);
foreach($look as $find){ if(strpos($find, $keyword) !== false) { if(!isset($highlight)){ $highlight[] = $find; } else { if(!in_array($find,$highlight)){ $highlight[] = $find; } } } }
if(isset($highlight)){ foreach($highlight as $replace){ $str = str_replace($replace,''.$replace.'',$str); } }
echo $str; ?>
The strip_tags() function strips a string from HTML, XML, and PHP tags.
Search and highlight the word in your string, text, body and paragraph:
".$string1." ".$string2; return $body; } ?>



Note: The strpos() function finds the sub string in a text using string matching method. Sometime it gives undesired result. For example: if string URL is https://www.geeksforgeeks.org/myfunction and sub string is function then sub string exist in the string URL. Suppose a website wants to display the result of function but it display the result of myfunction which is different. The strpos() function does not check if a sub string present as a whole or it is present with suffix or prefix.
Note: To solve this problem that is to find whether the exact pattern is present in a string(URL) or not preg_match() function is used.


Simple Recursive Find and Replace PHP CLI Script find-replace.php function isCli() { return php_sapi_name()==="cli"; }
function addCode($dir, $find, $replace, $str=''){ if (is_dir($dir)) { if ($dh = opendir($dir)) { $dirCount++; while (($file = readdir($dh)) !== false) { if( is_dir( $dir . $file ) ){ addCode($dir, $find, $replace, $str, $count); } else{ if( $str = '' ){ $temp = file_get_contents( $dir . $file ); $temp = str_replace($find, $replace, $temp); if( !file_put_contents( $dir . $file, $temp ) ){ echo "There was a problem (permissions?) replacing the file " . $dir . $file; } else{ echo "File " . $dir . $file . " replaced!"; $count++; } } else{ if(strpos($file,$str)){ $temp = file_get_contents( $dir . $file ); $temp = str_replace($find, $replace, $temp); if( !file_put_contents( $dir . $file, $temp ) ){ echo "There was a problem (permissions?) replacing the file " . $dir . $file; } else{ echo "File " . $dir . $file . " replaced!"; $count++; } } } } } closedir($dh); } else{ echo "There was a problem opening the directory " . $dir . " (permissions maybe?)"; } } else{ echo "You gave us a file instead of a directory, we could check that instead, but this is only designed for recursing really; use vim or something!"; } echo "Completed recursing" . $dir . "!"; }
if( isCli() ){ if( !isset($argv[1]) ){ echo "You need to specify a directory!"; } else if( !isset( $argv[2] ) ){ echo "You need to specify something to search for!"; } else if( !isset( $argv[3] ) ){ "You need to specify something to replace the search with!"; } else if( isset( $argv[4] ) ){ $dirArg = $argv[1]; $findArg = $argv[2]; $replaceArg = $argv[3]; $strArg = $argv[4]; echo "We're starting the search of all files in directory " . $dirArg . " that match filename containing " . $strArg . " recursively!"; addCode($dirArg, $findArg, $replaceArg, $strArg); echo "We replaced " . $count . " in " . $dirCount . " directories!"; } else{ $dirArg = $argv[1]; $findArg = $argv[2]; $replaceArg = $argv[3]; echo "We're starting the search of all files in directory " . $dirArg . " in all files recursively!"; addCode($dirArg, $findArg, $replaceArg); echo "We replaced " . $count . " in " . $dirCount . " directories!"; } } else{ echo "Can't run this shit from the web."; } ?>


// Sort in ascending order - this is default $a = scandir($dir);
// Sort in descending order $b = scandir($dir,1);
print_r($a); print_r($b); ?>



You can use useful glob(), internal PHP function
$files_in_your_folder = glob('c:\wamp\www\FindReplace\*');
So for your specific case:


What about this? It should take care of running your replace on all .txt-files, regardless of how many sub-folders you got in your path folder. foreach ($fileList as $item) { if ($item->isFile() && stripos($item->getPathName(), 'txt') !== false) { $file_contents = file_get_contents($item->getPathName()); $file_contents = str_replace("Paul",",HHH",$file_contents); file_put_contents($item->getPathName(),$file_contents); } } ?>
find /path/to/your/project -name '*.txt' -exec php yourScript.php {} \;
Then modify your script to use command line argument $argv[1] as the file path.


There's nothing built into PHP to do this. You'll have to write a script that uses glob() or scandir(), and recurses into all subdirectories. Then it has to use file_get_contents() on each file, str_replace() to do the replacement, and file_put_contents() to update the file. It will be much easier if you use a tool that's already built for this.
You can use glob to get all files in a directory, glob(__DIR__.'/*.php') will give you all php files in current directory. But if you need to do this in a production server only use it if you can run it as a command line function since the web server not should have write access to the files

Answer Active Oldest Votes 8
The preg_ functions uses the same regexp library that Perl does, so you should be at home. There's documentation of the syntax here.
For example:
sed -e 's/$pattern/$replace/g'
Would be something like:
$output = preg_replace("/".$pattern."/", $replace, $input);
The most common is to use / as delimiter, but you can use other characters, which can be useful if the pattern contains lots of slashes, as is the case with urls and xml tags. You may also find preg_quote useful.

Answers Active Oldest Votes 2
Your specific SED example is obviously 2 regular expressions, 1 being replacing the commas, and one being technically grabbing the 9 digit continuous numbers.
The first half of your SED string is best fit with the preg_replace() function.
//`sed s/regex/replace_value/flags`
preg_replace('/regex/flags', 'replace_value', $input);
The second half of your SED string would be a preg_match_all():
//`sed ...;s/regex/\1/flags`
$matches_array = array(); preg_match_all('/regex/flags', $input, &$matches_array);
So your specific code will look something like:
$input = preg_replace('/[, ]/m','', $input);
$matches = array(); //No need for the .* or groupings, just match all occurrences of [0-9]{9} if( preg_match_all('/[0-9]{9}/m', $input, $matches) ) { //... var_dump($matches); }
It l
ooks like g is an SED modifier meaning match all lines. preg_match_all() should already takes care of this modifier but m seems like an appropriate replacement as per the manual on PCRE modifiers. shareimprove this answer


Try using preg_replace() instead of preg_match(). grep is to sed what preg_match is to preg_replace.

preg_replace() is the function you are looking for. You can pass an array of patterns and replace parameters
$pattern = array('/[, ]/','/.*\([0-9]\{9\}\).*/'); $replace = array('','$1');
foreach($lines as $line) { $newlines[] = preg_replace($pattern, $replace, $line); }


function FixPHPText( $dir = "./" ){ $d = new RecursiveDirectoryIterator( $dir ); foreach( new RecursiveIteratorIterator( $d, 1 ) as $path ){ if( is_file( $path ) && substr($path, -3)=='php' && substr($path, -17) != 'ChangePHPText.php'){ $orig_file = file_get_contents($path); $new_file = str_replace("toString(", "invoke(",$orig_file); $new_file = str_replace(" split(", " preg_split(",$new_file); $new_file = str_replace("(split(", "(preg_split(",$new_file); if($orig_file != $new_file){ file_put_contents($path, $new_file); echo "$path updated
"; } } } }
echo "----------------------- PHP Text Fix START -------------------------
"; $start = (float) array_sum(explode(' ',microtime())); echo "
*************** Updating PHP Files ***************
"; echo "Changing all PHP containing toString to invoke and split to explode
"; FixPHPText( "." );
$end = (float) array_sum(explode(' ',microtime())); echo "
------------------- PHP Text Fix COMPLETED in:". sprintf("%.4f", ($end-$start))." seconds ------------------
"; ?>



search and replace multiple strings in multiple files (some with certain file name pattern) athletics-external-replace.php /*name pattern: $file_array = preg_grep("/^([a-z]{2,3}[0-9]{2}_[0-9]{4})(.*).htm$/i", $regex_filepath); select all files with name in the pattern ab(c)12_3456xxxx.htm */
$search = array ("old-style.css", "old-header.php", "old-footer.php"); $replace = array ("new-style.css", "new-header.php", "new-footer.php");
// go through all selected files, and perform a search and replace for multiple strings(css/header.php/footer.php) using array foreach ($regex_filepath as $filename) { $file = file_get_contents($filename); foreach ( $replace as $r ){ // need a needle to perform strpos with array if(strpos($file,$r)){ file_put_contents($filename, str_replace( $search, $replace, $file)); } } } ?>


// Counts lines in a file function countLines($filename) { $count = 0; if (file_exists($filename)) { $fh = fopen($filename, 'r'); if ($fh) { while (!feof($fh)) { $a = fgets($fh); $count++; } fclose($fh); } } return $count; }
// Scans directory; if it finds directory, calls itself function recursiveScan($dir) { // get a list of files in this directory $output = ''; $list = glob($dir . '/*'); // loop through list foreach ($list as $item) { // if directory print and call this function again if (is_dir($item)) { $output .= "$item"; $output .= recursiveScan($item); // otherwise output info as a table row } else { $size = filesize($item); $lines = countLines($item); $output .= sprintf("%s%d%d", basename($item), $size, $lines); } } return $output; }
?>

Recursive Directory Scan

File / Directory NameSizeLines