Re: Find Strings (Tokens) in File and push them into an array - How? [message #169606 is a reply to message #169592] |
Sat, 18 September 2010 21:15 |
Michael Fesser
Messages: 215 Registered: September 2010
Karma:
|
Senior Member |
|
|
.oO(Sherm Pendley)
> Michael Fesser <netizen(at)gmx(dot)de> writes:
>
>> .oO(aaaa)
>>
>>> And having 10 lines of fast, idiot understandable code is much better then
>>> having one line of regular expressions.
>>
>> That's just your opinion, not a fact.
>
> True, but it's an opinion that's shared by a *lot* of people. When it
> comes to maintenance, ten lines of readable code is *always* better
> than a "clever" one-liner.
Yes, but only _if_ it can be done in ten lines. When I use regular
expressions, I usually have a lot of optional and "dynamic" stuff in it:
arbitrary patterns, variable pattern lengths, special character classes,
alternative patterns and all these things. Doing that with just string
functions would require a lot of if-else constructs, switch statements
and a lot of additional checks.
If I then want to modify the behaviour by adding some other special case
for example, I might have to write a whole new code block instead of
just adding some chars to the regex pattern. Not to mention the fun you
might have when you want to recreate the behaviour of some of the PCRE
modifiers. For example doing things in a case-insensitive way might
require some whole checks to be written twice. In a regex it's just one
char.
And if a regex gets too complex, it makes sense to break it down into
pieces and comment it. Especially the last feature can make things much
easier to understand, but is rarely used.
A short note about the example posted by 'aaaa': I don't think his code
with all the exploding and trimming is so much clearer or better than
the posted regex. Sure you get the same result, but for me the regex
version is better because it's more written as intended and pretty much
self-explaining. You have some data, and you want to search for some
special pieces in it. The regex version does exactly that with a single
function call.
The code could even be shortened a bit. My version would be:
foreach ($files as $file) {
$text = file_get_contents($file);
preg_match_all('/\$__txt.+?;/', $text, $matches);
$tokens = array_merge($tokens, $matches[0]);
}
The function names already make completely clear what's going on.
The other version returns the same result, but works in a completely
different way, and from just looking at it it's IMHO not immediately
clear what it does. I have to walk through it and "execute" it in my
mind to understand what's going on.
Micha
|
|
|