I would like to put a text instead of the string VERSION=20101203, my problem is only the first field of preg_replace, I am new to regular expresions. I don't know exactly how to tell preg_replace to see that I need to change the string VERSION=20101203 for other text.
So the string has the format:VERSION=YEARMONTHDAY
I was trying with:
$new_content = preg_replace('/^VERSION\=[0-9]{8}/', $replacement, $content);
Where:
$replacement is the new string I want to have
$content is the content of a file that it doesn't matter here
I beleive it's not too difficult. Any questions you may have with this issue please ask me and I will answer quickly
Thank you very much in advance
^ is anchoring the regular expression to only the beginning of the line. I assume that's part of the problem.
$new_content = preg_replace('/VERSION\=[0-9]{8}/', $replacement, $content);
In addition, you will want to ensure that $replacement contains the full string for replacing the string matched by VERSION\=[0-9]{8}.
Try this code (without ^ at the start of regular expression):
$content='foo VERSION=20101203 foo bar';
var_dump( preg_replace('/VERSION=[0-9]{8}/', 'replacement', $content));
OUTPUT
string(23) "foo replacement foo bar"
Well it was solved with Jason McCreary's suggestion. It worked just without ^ and the rest of the code is the same as I had it before.
I was trying to change the string VERSION=YEARMONTHDAY (which is in one of the lines of the $ks file). I mean that the file contains in one of its lines this:
VERSION=20101203 (or any other date, but everytime with the same format)
That string is going to be changed by a new one that matches to the last modification of the file stored in the variable $ks. ($ks is the name of the file)
$last_modification = filemtime($ks);
$last_modification = date("Ymd", $last_modification);
// $last_modification (for instance suppose it is VERSION=20110622)
$last_modification="VERSION=" . $last_modification;
// Open the file in order to change the string
$file = $ks;
$fh = fopen($ks, 'r+');
$content = fread($fh, filesize($ks));
$new_content = preg_replace('/VERSION\=[0-9]{8}/', $last_modification, $content);
fclose($fh);
// Open the file in order to write inside it
$fh = fopen($ks, 'r+');
fwrite($fh, $new_content);
fclose($fh);
So the final result is going to be: the file named $ks will have a line with VERSION=20110622 instead of the VERSION=20101203 (or any other older date) string.
The code is working fine this way for me. Thank you all again, I don't know if I have to close this issue, as it is solved
PD: Sorry for my english
Related
I am writing an HTML file using file_put_content(), but want to be able to add additional content later by pulling the current file contents and chopping off the known ending to the html.
So something along these lines:
$close = '</body></html>';
$htmlFile = file_get_contents('someUrl');
$tmp = $htmlFile - $close;
file_put_contents('someUrl', $tmp.'New Content'.$close);
But since I can't just subtract strings, how can I remove the known string from the end of the file contents?
substr can be used to cut off a know length from the end of a string. But maybe you should determine if your string really ends with your suffix. To reach this, you can also use substr:
if (strtolower(substr($string, -strlen($suffix))) == strtolower($suffix)) {
$string = substr($string, 0, -strlen($suffix));
}
If the case not play any role, you can omit strtolower.
On the other side you can use str_replace to inject your content:
$string = str_replace('</body>', $newContent . '</body>', $string);
Maybe, Manipulate HTML from php could be also helpful.
I have string and I would like to remove words which are part of the string and in the array. The array was created using the file function and the preg_replace function to delete patterns from the array occurring within a sentence.
Although, I am not getting errors, the replace is not working. I would really appreciate any help, I have been trying to get it to work these last 3 days but I haven't managed to do so :( and it is driving me crazy.
This is what I have done so far:
PHP code:
$test=file('files/stop_words.txt');
echo $test;
$no_stop=str_replace('|$test|', 'lllll', $sentence);
echo "<br>" .$no_stop;
Stop_words.txt file excerpt:
|alone|
|along|
|alongside|
|already|
|also|
|although|
|always|
|am|
|amid|
|amidst|
|among|
|amongst|
|an|
Thanks
I am adding a sample sentence so you can see it working.
I swapped out file with file_get_contents so that you could remove the | on each side before doing the check.
str_replace can accept an array, but it must be setup for exact matches, so having "|among|" instead of just "among" would hinder as well.
$sentence = "I stood alone in the yard";
$test = file_get_contents('files/stop_words.txt'); // Load in as a string
$test = str_replace("|", "", $test); // Remove unneeded |
$testList = explode("\n", $test); // Turn into an array
$filtered_sentence = str_replace($testList, 'lllll', $sentence); // Pass array into str_replace
echo $filtered_sentence;
I have some content stored in a variable and it looks like"
$content = "This is a test content and the content of the url is http://www.test.com. The is a second sentence.";
Now my code is
$pos = strpos($content, '.');
$firstsentence = substr($content, 0, $pos);
The above code doesn't work as the string already contains a url having dots.
How can I get the first sentence considering the fact that a string contains a hyperlink?
Please share other scenarios of text. This works fine for your example:
$sentences = 'This is a test content and the content of the url is http://www.test.com. The is a second sentence.';
preg_match('/(http|https):(.*?)com/', $sentences, $match);
$sentences = preg_replace('/(http|https):(.*?)com/', '', $sentences);
$pos = strpos($sentences, '.');
$pos .= -1;
$firstsentence = substr($sentences, 0, $pos) .$match[0].'.';
//This is a test content and the content of the url is http://www.test.com.
In general, I think you're going to also have to look for <sentence-end-punct>"<whitespace>, "<sentence-end-punct><whitespace>, and <sentence-end-punct><whitespace> (where <whitespace> includes the end of a line). Is this very general English text, not especially under your control, or is the grammar very limited? For non-English text, there can be additional rules, such as putting spaces between punctuation and quotes.
Add: What are you trying to accomplish here? Do you really need to pull apart text into individual sentences, or are you just trying to create a "teaser". In the latter case, just cut off the text at a complete word before some number of characters, and add an ellipsis (...).
I need to find a specic line of text, from a text-file,
and then copy it to a new text-file:
1: I have a text file with several lines of text, eg:
JOHN
MIKE
BEN
*BJAMES
PETE
2: So, I read that text-files contents into an array,
with each line of text, placed into a seperate element of the array.
3: Then I tested each element of the array,
to find the line that starts with, say: *B ie:
if ( preg_match( "/^\*(B)/",$contents[$a] ) )
Which works ok...
4: Then I copy (WRITE) that line of text, to a new text-file.
Q: So how can I remove the '*B' from that line of text,
BEFORE I WRITE it to the new text-file ?
If you already use preg_match, you can modify your regex to get what you want in another variable.
if (preg_match('/^\*B(.*)$/', $contens[$a], $matches)
{
fwrite($targetPointer, $matches[1]);
}
After using preg_matchthe variable $matches holds the single matches of subparts of the regex enclosed in brackets. So the relevant part of your line ist matched by (.*) and saved into $matches[1].
This approach writes the lines as the file is read, which is more memory efficient:
$sourceFile = new SplFileObject('source.txt');
$destinationFile = new SplFileObject('destination.txt', 'w+');
foreach (new RegexIterator($sourceFile, '/^\*B.*/') as $filteredLine) {
$destinationFile->fwrite(
substr_replace($filteredLine, '', 0, 2)
);
}
demo
With substr or preg_replace.
Have a try with:
preg_replace('/^\*B/', '', $content[$a], -1, $count);
if ($count) {
fwrite($file, $content[$a]);
}
Hacking up what I thought was the second simplest type of regex (extract a matching string from some strings, and use it) in php, but regex grouping seems to be tripping me up.
Objective
take a ls of files, output the commands to format/copy the files to have the correct naming format.
Resize copies of the files to create thumbnails. (not even dealing with that step yet)
Failure
My code fails at the regex step, because although I just want to filter out everything except a single regex group, when I get the results, it's always returning the group that I want -and- the group before it, even though I in no way requested the first backtrace group.
Here is a fully functioning, runnable version of the code on the online ide:
http://ideone.com/2RiqN
And here is the code (with a cut down initial dataset, although I don't expect that to matter at all):
<?php
// Long list of image names.
$file_data = <<<HEREDOC
07184_A.jpg
Adrian-Chelsea-C08752_A.jpg
Air-Adams-Cap-Toe-Oxford-C09167_A.jpg
Air-Adams-Split-Toe-Oxford-C09161_A.jpg
Air-Adams-Venetian-C09165_A.jpg
Air-Aiden-Casual-Camp-Moc-C09347_A.jpg
C05820_A.jpg
C06588_A.jpg
Air-Aiden-Classic-Bit-C09007_A.jpg
Work-Moc-Toe-Boot-C09095_A.jpg
HEREDOC;
if($file_data){
$files = preg_split("/[\s,]+/", $file_data);
// Split up the files based on the newlines.
}
$rename_candidates = array();
$i = 0;
foreach($files as $file){
$string = $file;
$pattern = '#(\w)(\d+)_A\.jpg$#i';
// Use the second regex group for the results.
$replacement = '$2';
// This should return only group 2 (any number of digits), but instead group 1 is somehow always in there.
$new_file_part = preg_replace($pattern, $replacement, $string);
// Example good end result: <img src="images/ch/ch-07184fs.jpg" width="350" border="0">
// Save the rename results for further processing later.
$rename_candidates[$i]=array('file'=>$file, 'new_file'=>$new_file_part);
// Rename the images into a standard format.
echo "cp ".$file." ./ch/ch-".$new_file_part."fs.jpg;";
// Echo out some commands for later.
echo "<br>";
$i++;
if($i>10){break;} // Just deal with the first 10 for now.
}
?>
Intended result for the regex: 788750
Intended result for the code output (multiple lines of): cp air-something-something-C485850_A.jpg ./ch/ch-485850.jpg;
What's wrong with my regex? Suggestions for simpler matching code would be appreciated as well.
Just a guess:
$pattern = '#^.*?(\w)(\d+)_A\.jpg$#i';
This includes the whole filename in the match. Otherwise preg_replace() will really only substitute the end of each string - it only applies the $replacement expression on the part that was actually matched.
Scan Dir and Expode
You know what? A simpler way to do it in php is to use scandir and explode combo
$dir = scandir('/path/to/directory');
foreach($dir as $file)
{
$ext = pathinfo($file,PATHINFO_EXTENSION);
if($ext!='jpg') continue;
$a = explode('-',$file); //grab the end of the string after the -
$newfilename = end($a); //if there is no dash just take the whole string
$newlocation = './ch/ch-'.str_replace(array('C','_A'),'', basename($newfilename,'.jpg')).'fs.jpg';
echo "#copy($file, $newlocation)\n";
}
#and you are done :)
explode: basically a filename like blah-2.jpg is turned into a an array('blah','2.jpg); and then taking the end() of that gets the last element. It's the same almost as array_pop();
Working Example
Here's my ideaone code http://ideone.com/gLSxA