Need help with a twisty regexp / regexps

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Need help with a twisty regexp / regexps

Post by Chris Corbyn »

Hi,

I'm trying to write something that look at a given string, checks if there are any php tags present and if not, it'll stick em on. I was just gonna do it with a match and then do the concatenation separately (not using preg_replace).

I got the basic idea working with this regexp.
preg_match('/<\?php(.|\s)*?\?>/', $source))
but I need to make it more complex. I've been playing around all day to no avail. It needs to recognise when the php tags are sandwiched inside single or double quotes... tricky heh?

Examples and outputs (true=php tags do exist, false=php tags need adding):
This returns true:
<?php
echo $var;
?>

This returns true
<span>This isn't php</sapn>
<?php
echo 'But this is!';
?>

This returns false (That's the twist - those PHP tags aren't actually acting as PHP they are part of a string withing the PHP)

echo "An opening php tag looks like this <?php and a closing one looks like this ?>";

This also returns false (single quotes)
echo 'An opening php tag looks like this <?php and a closing one looks like this ?>';

But This returns true
<?php
echo 'An opening php tag looks like this <?php and a closing one looks like this ?>';
?>
Hope I have given a good enough idea of what I need to do. I'll post a better regexp if I get anywhere.

Hope somebody can offer some help *cough* cough* :lol: Feyd :? :lol:
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

sadly.. it's very challenging to do it correctly.. because you may match between sets of strings, if things are not laid out right.

on a side note: I finally fixed IE's CSS problem in

Code: Select all

.. so I expect to be able to update very soon. .. just a few more changes are needed
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Nice one. It'll be good when we get the

Code: Select all

tags back.

I know there's not really any point in doing the BBCode generator since they'll be back before I get all the bugs out of this but I'm just gonna finish this to put in my projects folder and it's kinda interesting to learn how to make it work.

I'm gonna look closer at that code you showed me before
Post Reply