Reputation: 1190
I'm trying to match numbers and replace them with (matched number)px
The thing is that I want to match them ONLY when they're not part of a hex color code. My input can contain hex color codes in two ways:
#xxx
or #xxxxxx
where the x
can be a letter from a-f
or a number from 0-9
.
The regex I currently have is this:
$input = preg_replace('/(?<!#..)(\d)(?!px)/i', '$1px', $input);
This works only with a 3 digit hex code and that too only when the digit is at the third place.
I want something applicable in all situations. This should replace only those numbers that are not part of a hex code and don't already have a px
after them. Thanks!
EDIT: since negative lookbehind can't contain an indefinite number of characters (no quantifiers that is) I have no idea what to do.
The input and output should be like:
input: #da4 10 output: #da4 10px
input: #122222 10 output: #122222 10px
input: #4444dd 20px output: #4444dd 20px
input 30 10 20 20 #414 20 99 #da4 output: 30px 10px 20px 20px #414 20px 99px #da4
Upvotes: 0
Views: 68
Reputation: 1688
Regex:
\b(?<!#)\d+\b
# \b Assert position at a word boundary
# (?<!#) Negative Lookbehind
# \d+ Match a number with 1 to ilimited digits
# \b Assert position at a word boundary
$input = '30 10 20 20 #414 20 99 #da4 #122222 10 #4444dd 20px';
$input = preg_replace('/\b(?<!#)\d+\b/', '$0px', $input);
print($input);
Upvotes: 1
Reputation: 43166
You can use (?<!#)\b(\d+)\b(?!px)
(replace with $1px
).
Demo.
Explanation:
(?<!#) make sure this isn't hex
\b make sure we're matching the whole number, not just a part of it
(\d+) capture the number
\b again, make sure we've captured the whole number
(?!px) make sure there's no px
Upvotes: 1