Fgets() but on a string instead of a file?
I can do the following:
$fopen = fopen($file_name, '开发者_JAVA技巧r');
$data = fgets($fopen, 16384);
fclose($fopen);
But is their any way I could emulate the same functionality but on a string (instead of using a file name)?
$string = file_get_contents($file_name); /* just for demonstration purposes */
$data = /* do something here...*/
Hope that made sense.
There are lots of function defined for String manipulation here. You can choose any of them which fulfills your requirements.
Probably you need substr()
This manual page documents a custom stream wrapper that can be used to give
read/write access to a named global variable using standard filesystem stream functions such as fread(). The var:// protocol implemented below, given the URL "var://foo" will read/write data to/from $GLOBALS["foo"].
This would allow you to do:
$fp = fopen('var://string', 'r');
$data = fgets($fp, 16384);
to 'fread() from $string'.
$parts = explode("\n", $data);
foreach ($parts as $key => $value) {
$parts[$key] = substr($parts[$key], 0, 16384);
}
I like internal pointers too. You can always:
$fp = fopen('php://memory', 'r+');
fwrite($fp, $string);
rewind($fp);
I also saw a one-liner equivalent that goes like this:
$fp = fopen('data://text/plain;base64,' . base64_encode($string), 'r');
... which is elegant but has the caveat of a redundant encoding step.
$string = file_get_contents($file_name); /* just for demonstration purposes */
$data = substr($string, 0, 16384);
Or maybe do you want ton consume a part of the string for each call to the function?
Humm... Not sure what you want but have you looked into substr()
?
精彩评论