Help with regular expressions to edit strings

Discussion in 'PHP' started by James WP, Feb 24, 2010.

  1. #1
    I have a number of dynamically generated strings that take the form:

    These Words are Always Different X ab

    ...where " X ab" (with space before) may or may not be present. If it is present, then "X" may be any character, while "ab" will always be those two characters.

    What I want to do is remove " X ab" if it is there, but since I don't always know what "X" is, I think this will require regular expressions. I can't just test whether "ab" is at the end and then delete the last 5 characters, because the presence of "ab" does not guarantee the presence of " X ".

    Can anyone suggest the code to achieve this? Many thanks.
     
    James WP, Feb 24, 2010 IP
  2. s_ruben

    s_ruben Active Member

    Messages:
    735
    Likes Received:
    26
    Best Answers:
    1
    Trophy Points:
    78
    #2
    Try this:

    preg_replace("/ . ab/","",$string)
    Code (markup):
     
    s_ruben, Feb 24, 2010 IP
  3. James WP

    James WP Active Member

    Messages:
    42
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    91
    #3
    Great, that seems to work, thanks! :)
     
    James WP, Feb 24, 2010 IP
  4. s_ruben

    s_ruben Active Member

    Messages:
    735
    Likes Received:
    26
    Best Answers:
    1
    Trophy Points:
    78
    #4
    But it outputs:

    Before: These Words are Always Different X ab
    After: These Words are Always Different

    Maybe your server doesn't support preg_replace function?
     
    s_ruben, Feb 24, 2010 IP
  5. James WP

    James WP Active Member

    Messages:
    42
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    91
    #5
    Sorry, I must have edited my post while you were replying.

    It does work for the example I've given, so the function seems to be correct. Unfortunately it doesn't work for the actual strings I'm using, which appear to have unusual characters in them. In truth I know what "X" is always going to be, but I can't seem to replicate this character - even via copy and paste - so no amount of checking I do in my code is picking it up and replacing it.

    Thanks for your help, but I think I'd be dragging you into too big a mess if we keep trying to resolve my very specific issue here.
     
    James WP, Feb 24, 2010 IP