php replace a pattern - php

Suppose in a file there is a pattern as
sumthing.c: and
asdfg.c: and many more.. with *.c: pattern
How to replace this with the text yourinput and save the file using php
The pattern is *.c
thanks..

You can read the contents of the file into a PHP string using file_get_contents, do the *.c to yourinput replacement in the string and write it back to the file using file_put_contents:
$filename = '...'; // name of your input file.
$file = file_get_contents($filename) or die();
$replacement = '...'; // the yourinput thing you mention in the quesion
$file = preg_replace('/\b\w+\.c:/',$replacement,$file);
file_put_contents($file,$filename) or die();

You can use PHP's str_replace or str_replace ( in case its a regex pattern). CHeck the syntax of these two functions and replace the *.c with your input.
.c pattern should be something like /?(.c)$/

First open file and get it's content:
$content = file_get_contents($path_to_file);
Than modify the content:
$content = preg_replace('/.*\.c/', 'yourinput');
Finally save the result back to the file.
file_put_contents($path_to_file, $content);
Note: You may consider changing the regexp because this way it match the '.c' string and everything before it. Maybe '/[a-zA-Z]*\.c/' is what you want.

Related

How i can delete some data-attributes with value in file-content?

I want to delete some data-attributes with they values inside the sourcecode of a file.
I load the file inside a variable
$filecontent = file_get_contents($pathtofile);
Now I want to delete some code, for example
delete data-myval="something123"
Important to know is, that the value "something123" is dynamically.
How I can delete all matches of data-myval="find_all"
I tried to do it with str_replace and explode failed, it was to complicated and produced too long of code.
Is there a easier way to do it?
Thanks a lot.
You can achieve this using preg_replace. This will allow you to match any regex expressions and remove the code.
Your regex expression will be (see regex101):
data-myval\=\"[^"]+\"
Using preg_replace:
$filecontent = file_get_contents($pathtofile);
$filecontent = preg_replace('/data-myval\=\"[^"]+\"/', '', $filecontent);
After this you will need to save the file using file_put_contents().
file_put_contents($pathtofile, $filecontent);

PHP file_get_contents() not working when + (plus) sign is in file name

I have a couple of files that have the plus sign in their name, and I cannot seem to be able to open them, as the function interprets it as a space.
Example:
File name: Report_Tue-Jun-02-2015-14:11:04-GMT+0200-(W.-Europe-Daylight-Time).html
And when I try to open it:
Warning: file_get_contents(/cores/Report_Tue-Jun-02-2015-14:11:04-GMT 0200-(W.-Europe-Daylight-Time).html) [function.file-get-contents]: failed to open stream: No such file or directory in .... on line 150
this is my code:
$file = $_GET['FILE'];
$file = str_replace('+', '%2B', $file);
$content = file_get_contents($file);
Any thoughts/solutions?
The following methods work fine for me.
<?
# File name: Report_Tue-Jun-02-2015-14:11:04-GMT+0200-(W.-Europe-Daylight-Time).html
# Method 1.
$file = 'Report_Tue-Jun-02-2015-14:11:04-GMT+0200-(W.-Europe-Daylight-Time).html';
$data = file_get_contents($file);
print($data);
# Method 2.
$data = file_get_contents('Report_Tue-Jun-02-2015-14:11:04-GMT+0200-(W.-Europe-Daylight-Time).html');
print($data);
?>
Information how to write a valid URI is available in RFC3986. First, You need to take care that all special characters are represented correctly. e.g. spaces to plus-signs, and the commercial at sign has to be URL encoded.
Also superfluous whitespace at beginning and end need to be removed. Using function urlencode() for entire URL, will generate an invalid URL. Leaving the URL as it is also is not correct, because in contrast to the browsers, the file_get_contents() function does not perform URL normalization. In your example, you need to replace plus sign with %2B:`
$string = str_replace('+', '%2B', $string);
This is what eg. encodeURIComponent() does in JavaScript. Unfortunately it's not what urlencode does in PHP (rawurlencode is safer). check also the link
I hope this will work for you.
First of all file should not contain : sign.
Then the below code works fine for me.
$content = file_get_contents('Report_Tue-Jun-02-2015-141104-GMT+0200-(W.-Europe-Daylight-Time).html');
echo $content;
If not worked, please use:
$link = urlencode($url);
$content = file_get_contents($link);
echo $content;
I think its work each time.

str_replace not working with txt file PHP

str_replace doesn't seem to be working as we expect it to.
We have a text file and we're trying to remove part of the file.
while(!feof($bodyfile)) {
$content = #fgets($bodyfile);
$content = str_replace("MARGIN","",$content);
(Obviously fopen is used to open the file as 'r')
Strangely enough, finding and replacing M works? but not margin..
UPDATE:
fgets() function reads only 1 line at the time, and by putting that line in your $content variable, you're overwriting the replacement for previous line, and doing it over and over again.
Try with this:
$content = "";
while(!feof($bodyfile)) {
$line = #fgets($bodyfile);
$content .= str_replace("MARGIN","",$line);
So, what this code does is reading the line and assigning it to the $line variable, and then adding the replaced string to your $content variable.
By adding # sign in front of your functions, you're suppressing errors which that function gives.
Try to remove # from your #fgets and see if there's any error.
Try var_dump($content) or echo $content to see if file is loaded correctly.
Remember that str_replace() is case sensitive.
you could do:
$str=implode("",file('somefile.txt'));
$fp=fopen('somefile.txt','w');
$str=str_replace('MARGIN','',$str);
//OR
//$str=str_ireplace('MARGIN','',$str); for case insensitivity
fwrite($fp,$str,strlen($str));
Just found out the file is a UTF-16 character encoding rather than UTF-8 for some obscure reason. Converted, now my method originally works!
Thanks to all for suggestions

regex to get current page or directory name?

I am trying to get the page or last directory name from a url
for example if the url is: http://www.example.com/dir/ i want it to return dir or if the passed url is http://www.example.com/page.php I want it to return page Notice I do not want the trailing slash or file extension.
I tried this:
$regex = "/.*\.(com|gov|org|net|mil|edu)/([a-z_\-]+).*/i";
$name = strtolower(preg_replace($regex,"$2",$url));
I ran this regex in PHP and it returned nothing. (however I tested the same regex in ActionScript and it worked!)
So what am I doing wrong here, how do I get what I want?
Thanks!!!
Don't use / as the regex delimiter if it also contains slashes. Try this:
$regex = "#^.*\.(com|gov|org|net|mil|edu)/([a-z_\-]+).*$#i";
You may try tho escape the "/" in the middle. That simply closes your regex. So this may work:
$regex = "/.*\.(com|gov|org|net|mil|edu)\/([a-z_\-]+).*/i";
You may also make the regex somewhat more general, but that's another problem.
You can use this
array_pop(explode('/', $url));
Then apply a simple regex to remove any file extension
Assuming you want to match the entire address after the domain portion:
$regex = "%://[^/]+/([^?#]+)%i";
The above assumes a URL of the format extension://domainpart/everythingelse.
Then again, it seems that the problem here isn't that your RegEx isn't powerful enough, just mistyped (closing delimiter in the middle of the string). I'll leave this up for posterity, but I strongly recommend you check out PHP's parse_url() method.
This should adequately deliver:
substr($s = basename($_SERVER['REQUEST_URI']), 0, strrpos($s,'.') ?: strlen($s))
But this is better:
preg_replace('/[#\.\?].*/','',basename($path));
Although, your example is short, so I cannot tell if you want to preserve the entire path or just the last element of it. The preceding example will only preserve the last piece, but this should save the whole path while being generic enough to work with just about anything that can be thrown at you:
preg_replace('~(?:/$|[#\.\?].*)~','',substr(parse_url($path, PHP_URL_PATH),1));
As much as I personally love using regular expressions, more 'crude' (for want of a better word) string functions might be a good alternative for you. The snippet below uses sscanf to parse the path part of the URL for the first bunch of letters.
$url = "http://www.example.com/page.php";
$path = parse_url($url, PHP_URL_PATH);
sscanf($path, '/%[a-z]', $part);
// $part = "page";
This expression:
(?<=^[^:]+://[^.]+(?:\.[^.]+)*/)[^/]*(?=\.[^.]+$|/$)
Gives the following results:
http://www.example.com/dir/ dir
http://www.example.com/foo/dir/ dir
http://www.example.com/page.php page
http://www.example.com/foo/page.php page
Apologies in advance if this is not valid PHP regex - I tested it using RegexBuddy.
Save yourself the regular expression and make PHP's other functions feel more loved.
$url = "http://www.example.com/page.php";
$filename = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_FILENAME);
Warning: for PHP 5.2 and up.

Find and replace in a file

I want to replace certain strings with another one in a text file (ex: \nH with ,H). Is there any way to that using PHP?
You could read the entire file in with file_get_contents(), perform a str_replace(), and output it back with file_put_contents().
Sample code:
<?php
$path_to_file = 'path/to/the/file';
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace("\nH", ",H", $file_contents);
file_put_contents($path_to_file, $file_contents);
?>
There are several functions to read and write a file.
You can read the file’s content with file_get_contents, perform the replace with str_replace and put the modified data back with file_put_contents:
file_put_contents($file, str_replace("\nH", "H", file_get_contents($file)));
If you're on a Unix machine, you could also use sed via php's program execution functions.
Thus, you do not have to pipe all of the file's content through php and can use regular expressions. Could be faster.
If you're not into reading manpages, you can find an overview on Wikipedia.
file_get_contents() then str_replace() and put back the modified string with file_put_contents() (pretty much what Josh said)

Categories