I need a regular expression to detect the phrase Figure 1.5: in a given string. Also, I intend on using this expression in a PHP preg_replace() function.
Here are some more examples:
- …are given.
Figure 2.1:shows that… - …are given.
Figure 3:shows that… - …are given.
Figure 1.16:shows that… - …are given.
Figure 0.4shows that… - …are given.
figure 5.1:shows that…
With my limited Regex knowledge, I was able to create this:
/wFigure d*.?d*/g
But that doesn’t even begin to handle all of the permutations that could occur.
I would appreciate any suggestions that you might have.
Advertisement
Answer
There are several points here:
- You are using
wat the start, perhaps, as a word boundary. In fact,wmatches a letter, digit or_and actually requires this char to be at the exact location. However, there is no word char beforeFigure, so you need to either removewor replace withb. preg_replacereplaces all non-overlapping occurrences by default, you do not need thegmodifierd*.?d*is fine here, but since you want to match any digits followed with zero or more occurrences of.and digits you can use a more specific pattern liked+(?:.d+)*.
You can use
preg_replace('/Figure d+(?:.d+)*/', '', $string)
See the regex demo.
Details:
Figure– a string– a space (replace withs+to match any one or more whitespaces, and consider addinguflag after last/if you need to find all Unicode whitespaces)d+– one or more digits(?:.d+)*– zero or more occurrences of.and one or more digits.