I don't have any expirience in regex with php (just some copy/pasting for simple tasks) so I can't 'solve' simple situatio, and I hope that somone can help.
I have a lage files that look like:
xxxxxxxxxxxxxx
xxxxxxxxxxxxxxx
xxxxxxxxxxxxxx
text,text,text,
text,text,tec,etc
Now i need in php to write function where passed string with content like this will return me part that I marked here as 'xxx...'
After every 'xxxx...' sequence at file begin, I have as you can see new line (\r\n) and I don't know how to use regex to to cut upper part into another string, so please help.
I'd skip the regex.
$eol = strpos($s, "\r\n");
$header = substr($s, 0, $eol);
$rest = substr($s, $eol + 2);
If the only part of the string separated by two new lines is the header series of 'xxxx' and the following 'text,text,text' lines, you could simply use explode. Passing a limit of 2 means it will only explode at the first instance of "\n\n", returning an array of at most 2 items:
list($header, $body) = explode("\n\n", $file_contents, 2);
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.
How can I add a new line characters (\n\r) in txt file every 10 characters?
What I have is a long sequence of characters, and I like to create a new line for each 10 characters.
in example, let's say I have that sequence of characters:
FadE4fh73d4F3fab5FnF4fbTKhuS591F60b55hsE
and I like to convert it to that:
FadE4fh73d
4F3fab5FnF
4fbTKhuS59
1F60b55hsE
How can I do that ?
I know that I can use a loop for that, but because the above string is an example and my string that I have to split it is really very very long, just I wander if there is any faster and more easy way to spit my string.
chunk_split($string, 10)
http://php.net/manual/en/function.chunk-split.php for more info
using chunk_split():
$str = chunk_split($str, 10, "\n\r");
or using this regex:
$str = preg_replace("/(.{10})/", "$1\n\r", $str);
And by the way did you mean \r\n (New line in Windows environment) by \n\r?
if so then the third argument for chunk_split() can be omitted.
<?php
$foo = '01234567890123456789012345678901234567890123456789012345678901234567890123456789';
$result = chunk_split ($foo, 10, "\r\n");
echo $result;
?>
As mentioned above, the use of chunk_split() might have unwanted consequences, as the break sequence is always added to the end once again.
You can instead use a combination of str_split() and implode() to first split the string every X characters and then recombine it with a break sequence. By using implode(), the break sequence will not be added to the end, again.
I've build a helper function who does this for me after 75 chars:
function createFold($s, $b = '\\n ') {
$chunks = str_split($s, 75);
return implode($b, $chunks);
}
<b><</b>?<b>php</b><br/>
$body=$row['details'];<br/>
$str = chunk_split($body, 14, "<b><</b><b>br</b><b>/</b>");<br/>
echo $str;<br/>
?
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
I'm currently developing a script that takes a message, splits it apart every 100 characters or so, and sends each part.
However, my original string has "\n" lines in it, and this is causing an issue with my preg_split, causing it to split pre-maturely (e.g., before 100 characters).
Here's what I am currently working with:
$sMessage = "Msg from John Smith \n".
"SUBJ: Hello! \n".
"This is the bulk of the message and can be well over 200 or 300 characters long. \n".
"To reply, type R 131, then ur msg.";
$split = preg_split('/(.{0,100})\s/',
$sMessage,
0,
PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
array_shift($split);
$count = count($split);
foreach ($split as $key => $message) {
$part = sprintf("(%d/%d) %s", $key+1, $count, $message);
echo $part;
echo "<br>";
}
Now, with this, I've noticed 3 things:
1) The first part of the message ("Msg from John Smith") does not even get included in the array.
2) The new lines (\n) seem to cut the string early.
3) Oddly enough, with the last line of the message ("To reply" etc...) it cuts off the last word ("msg.") and adds that into a new line, no matter what the sentence may read.
Any help on this would be great!
You are actually trying to reimplement the function wordwrap(). I think the call that does the job you need would look like this:
$array = explode("\n", wordwrap($string, 100, "\n", true));
my original string has "\n" lines in it
Use the PCRE_DOTALL modifier to allow ‘.’ to match newlines.
Chunking a string into an array of fixed-length strings can more easily be done using str_split. As soulmerge suggests, wordwrap is probably better if that's what you're really trying to do. You can use explode to split a string out to an array afterwards.
Avoid resorting to regex where string processing functions are available. (And PHP has a lot.)
I have a variable that needs the first four lines stripped out before being displayed:
Error Report Submission
From: First Last, email#example.com, 12345
Date: 2009-04-16 04:33:31 pm Eastern
The content to be output starts here and can go on for any number of lines.
I need to remove the 'header' from this data before I display it as part of a 'pending error reports' view.
Mmm. I am sure someone is going to come up with something nifty/shorter/nicer, but how about:
$str = implode("\n", array_slice(explode("\n", $str), 4));
If that is too unsightly, you can always abstract it away:
function str_chop_lines($str, $lines = 4) {
return implode("\n", array_slice(explode("\n", $str), $lines));
}
$str = str_chop_lines($str);
EDIT: Thinking about it some more, I wouldn't recommend using the str_chop_lines function unless you plan on doing this in many parts of your application. The original one-liner is clear enough, I think, and anyone stumbling upon str_chop_lines may not realize the default is 4 without going to the function definition.
$content = preg_replace("/^(.*\n){4}/", "", $content);
Strpos helps out a lot: Here's an example:
// $myString = "blah blah \n \n \n etc \n \n blah blah";
$len = strpos($myString, "\n\n");
$string = substr($myString, $len, strlen($myString) - $len);
$string then contains the string after finding those two newlines in a row.
Split the string into an array using split(rex), where rex matches two consecutive newlines, and then concatenate the entire array, except for the first element (which is the header).