0

I am trying to save a random line from a file to a variable ($fortune), that part is easy. The part that I am having trouble with is the "line" can be multiple lines. Every line will end with \n% (enter key plus %). How would I get this to a variable? An example of the file is below:

"There is a wiki on iptables http://en.wikipedia.org/wiki/Iptables and don't mess around with iptables - it's really tricky"

Husse Mar 15 2007

%

"The Ubuntu developers have gone to great lengths to make sudo as smooth as possible in the GUI environment, and they've done a very good job. By re-enabling the root user and even logging in as root, you literally throw their work out the window, take your safety belt off and drive head-on into traffic. Yes, it is a bit insane.."

Husse Mar 20 2007

%

(It would pick everything before a "%")

Community
  • 1
  • 1

2 Answers2

1

Try:

$array = explode("\n%\n", $text);

print_r($array);

Or:

$array = array_map('trim', explode("%", $text));

print_r($array);

Where $text is the string that you read from the file.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
0

Have you considered using a regular expression to catch all of that?

Rather chunked, but here is what I got:

php > preg_match("/%(.*?)%/s", $str, $arr);
php > print_r($arr);
Array
(
    [0] => %
my fortune is quite the ugly one

litterally
%
    [1] => 
my fortune is quite the ugly one

litterally

)

Its not the most optimal regualr expression, and I basically took my inspiration from here: Regex, get string value between two characters

But it should get you started!

Community
  • 1
  • 1
Ingwie Phoenix
  • 2,703
  • 2
  • 24
  • 33