Aidan's PHP Repository

A repository for PHP functions and classes ...

function.text2array.php

Convert a block of text to a trimmed, filtered array.

Indepdent of the line endings used.

  • Author: Aidan Lister <aidan@php.net>
  • Version: 1.1.0
  • Link: http://aidanlister.com/repos/v/function.text2array.php
  • Views: 5458
  • Downloads: 487

Source

Download this script <?php
/**
 * Convert a block of text to a trimmed, filtered array.
 *
 * Indepdent of the line endings used.
 *
 * @author      Aidan Lister <aidan@php.net>
 * @version     1.1.0
 * @link        http://aidanlister.com/repos/v/function.text2array.php
 * @param       string      $text      Text
 */
function text2array($text)
{
    $array = preg_split('#(\r\n?|\n)#', $text, -1, PREG_SPLIT_NO_EMPTY);
    $array = array_map('trim', $array);
 
    return $array;
}
 
?>

Example

<pre>
<?php
require_once 'function.text2array.php';
 
// The user is asked to provide a list of search keywords (for example)
$userinput = 'a
list
of
 
 keywords
 to be used';
 
// Explode
$keywords = text2array($userinput);
 
// Display list of keywords
print_r($keywords);
 
?>
</pre>

Output

Array
(
    [0] => a
    [1] => list
    [2] => of
    [3] => keywords
    [4] => to be used
)

Comments

June 6th, 2006
I used it to do advanced calculations on a supplied text string. Thank you for the clean function.
July 11th, 2005
Hi, I've put an example up. The main benifit of this function is the line-ending independence. Mac uses \r, Windows uses \r\n, so the frequently used PHP code will not work as expected.
July 11th, 2005
I don't really see the usefullness of this, could you please provide an example?