Php > Miscellaneous
Using data from a string
Using data from a string // I wrote this function in response to someone's question on the PHP-DB mailing // list. What they wanted to do was get the output of a curl function and break it // up into variables that they can use. You can (if you want) specify the newline // separator as well as the the name/value separator. Default newline is '\n' and // default name/value separator is '='. header("Content-Type: text/plain"); $strText = "Name1=Value1 \n Name2 = Value 2\nName 3 =Value 3"; $arrPairs = extractPairs($strText); print_r($arrPairs); //Output: Array ( [Name1] => Value1 [Name2] => Value 2 [Name 3] => Value 3 ) //And here's the function you can use // this one splits with \n and = $arrPairs = extractPairs($strText); // this one splits with \n and -- $arrPairs = extractPairs($strText,"--"); // this one splits with
and --> $arrPairs = extractPairs($strText,"-->","
"); function extractPairs($strText,$strValueSeparator="=",$strNewlineSeparator="\n"){ // kill the bad stuff... prevent a meaningless array if (!is_string($strText)){ return array(""=>""); } // gets rid of newlines/spaces etc so we don't get a crap array $strText = trim($strText); // separate each line in an element in an array $arrLines = explode($strNewlineSeparator,$strText); // loop through $arrLines, separating the // names/values and placing them in $arrOutput for ($i=0;$i
Php Codes
Algorithms
Arrays
Authentication
Calendar
Code Snippets
Programs
Content Manage
Contest Related
Cookies
Credit Cards
DBase Related
Databases
Date Time
Directories
E-Mail
Errors
File
File System
Forms
Handling
Graphics
HTML and PHP
Informix
Ingres
InterBase
LDAP
Look and Feel
Miscellaneous
MySQL
Other
PHP Classes
Searching
Navigation
Statistics
Strings
User Manage