Announcement

Collapse
No announcement yet.

Regular Expressions

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Regular Expressions

    I have two questions regarding regular expressions:

    1. When forming the pattern, does it matter if you use '#' or '/' ?

    eg: '#<phrase name="(.*?)" />#i'' or '/<phrase name="(.*?)" />/i'

    2. You can use preg_replace() to replace data with an advanced pattern, and you can use $1 to use a string from your pattern

    eg: preg_replace( '#\[b\](.*?)\[b\]#i', '<strong>$1</strong>', $text );

    Is there a way to use the $1 elsewhere in your code, outside of the preg_replace statement?
    Bugdar: PHP bug tracking software that is beautiful, fast, and robust.

  • #2
    1. I don't think that it matters, but I could be wrong. I tend to use #'s.
    2. You can pass the \\1 to a function, and then PHP can execute from there. You can do this by using the e pattern modifier. For example, this out of my custom code parser (very simple):
    PHP Code:
    $txt preg_replace("#\[color=(.*?)\](.*?)\[/color\]#sie""\$this->parseColor('\\1', '\\2')"$txt); 
    Its used in a class, so the parseColor function is a method within the class.

    Comment


    • #3
      Originally posted by daemon
      1. When forming the pattern, does it matter if you use '#' or '/' ?

      eg: '#<phrase name="(.*?)" />#i'' or '/<phrase name="(.*?)" />/i'
      No, it doesn't matter, as said before. It appears that there's lots of different things you can use, ~ being one of them. I tend to use /'s, even though #'s are easier to use (generally due to the fact that you're more likely to have /'s in the regex itself than #'s, which makes /'s more confusing to escape.
      "63,000 bugs in the code, 63,000 bugs, you get 1 whacked with a service pack, now there's 63,005 bugs in the code."
      "Before you critisize someone, walk a mile in their shoes. That way, when you critisize them, you're a mile away and you have their shoes."
      Utopia Software - Current Software: Utopia News Pro (news management system)

      Comment


      • #4
        Originally posted by CeleronXT
        No, it doesn't matter, as said before. It appears that there's lots of different things you can use, ~ being one of them. I tend to use /'s, even though #'s are easier to use (generally due to the fact that you're more likely to have /'s in the regex itself than #'s, which makes /'s more confusing to escape.
        Yeah... I'm starting to use '#' because it looks less confusing when you have to escape a whole bunch of characters.

        Thanks for the help Chorder and CeleronXT
        Bugdar: PHP bug tracking software that is beautiful, fast, and robust.

        Comment

        widgetinstance 262 (Related Topics) skipped due to lack of content & hide_module_if_empty option.
        Working...
        X