2
votes

I'm having trouble using Regex to replace strings that have a ? in between two characters. Two examples of what I'd like Regex to match are:

• Replace thi?s question mark but not this one?
• ? Replace the lonely question mark

What's the best way to:

a) Match a character surrounded by other characters

b) Match a character that is on it's own and has no characters before it or after it

I'm using PHP preg_match and MySQL REGEXP to preform these pattern matchings. For MySQL I've tried:

SELECT description
FROM locations
WHERE description
REGEXP '/|([^?]+)\/'

For PHP I've tried:

preg_match('/|([^?]+)\/', $string);
2
So what problem did you run into? - devnull
Ah! Nice avatar. What's in there? - devnull
@devnull Every pattern I try doesn't yield the results I'm looking for. - Enijar
@Enijar Could you mention a couple of those that you tried? - Jerry

2 Answers

1
votes

Check this Demo Code Viper

Pattern

/(\w+)?(\w+)/g

Test this Pattern


PHP

<?php
    echo preg_replace("/(\w+)?(\w+)/i", "thi?s", "?");
?>

Result

?

Hope this help you!

1
votes

I suggest this one for PHP:

(?<!\w(?=\? ))\?(?!\s*$)\s*

(?!\s*$) is a negative lookahead that will prevent a ? from matching if it is at the end of a sentence (I added whitespaces just in case).

(?<!\w(?=\? )) is a little more complex. It will prevent a match if the ? is preceded by a \w character (typically read as [a-zA-Z0-9_]) and followed by a space.

regex101 demo

I don't know whether mysql supports lookbehinds though.


|([^?]+)\

This is your current regex and I don't think your PHP code runs. The \ at the end is not escaping anything (in fact, it's trying to escape the delimiter) so... :s