PDA

View Full Version : How to get a part of string using an iterative method


nst
05-13-2007, 12:46 PM
Assuming I have the following line from a text file
define ('THIS_IS_A_TITLE', 'My data for this title');

which I load into a variable, therefore

$line = define ('THIS_IS_A_TITLE', 'My data for this title')

My purpose is to get two variables from that like

$title = THIS_IS_A_TITLE
$data = My data for this title

How would you do that? I thought of counting the ' characters, then $title begins after the 1st ' and ends before the 2nd, whilst $data begins after the 3rd ' and ends before the 4th.

But maybe there is a more elegant way. Any ideas?

Thanks.

P.S There are of course more $title and $data, $line would be a part of an array of lines from a text file, that is why I say an iterative method.

GJay
05-13-2007, 01:31 PM
There is almost certainly a better way to do whatever it is you're doing. When something smells odd, it normally is.

Would get_defined_constants() (http://uk2.php.net/manual/en/function.get-defined-constants.php) be of any use? It returns an array of defines and their values (the 'user' portion is what's going to be of use).
Or could this text file be in some other format that is more easily parseable? (ini, yaml, xml, json, etc.)

Otherwise, a regexp will make things a little bit nicer:

$pattern = "#define\('([A-Z_]+)','([^']+)'\)#";

(untested, but should be close...)
this won't take into account strings with escaped quotes in though,

define('SOMETHING','John O\'Reilly');

for example.

nst
05-13-2007, 02:31 PM
Hi,

get_defined_constants() displays all system constants, I do not know how to limit them. Could you also tell me, btw, how it is possible to make print_r change line when the output is put on the browser?

File format cannot be changed now, it is a part of a large application.

I will check the regexp solution, later.


Thank you.