带有preg_replace的REGEX不能与括号匹配吗?

时间:2018-09-24 03:25:52

标签: php regex preg-replace

preg_replace是否与图片名称中的括号冲突?

这是我的代码:

Pattern: /\/images\/upload\/image\/201808\/thumbnail(3).jpg/

Replacement: some_domain_url/images/upload/image/201808/thumbnail(3).jpg

Content: <img src="/images/upload/image/201808/thumbnail(3).jpg" alt="" />

结果:不替代。我尝试用%28替换括号,而%29也不起作用。

添加:模式和替换存储在动态数组中。必须用REGEX代替。目的是将所有本地映像路径替换为云存储。

任何REGEX专业人士都可以提供建议吗?

2 个答案:

答案 0 :(得分:0)

您需要像这样转义括号:

def checkit(a):
    try:
        slicedVal = str(int(a[0:3])) + '-' + str(int(a[4:6])) + '-' + str(int(a[7:11]))
        print(slicedVal)
        # Caution!
        # If you want to match exactly the number of digits in the last portion of xxx-xx-xxxx variable
        # the slice or the assert statement will not catch this error or fail
        # Slicing a string with a number greater than it's length will pass without errors
        # e.g.
        # >>> print('I will pass'[0:2000])
        # I will pass
        assert slicedVal == a, "FAIL"
        print("True")
        return slicedVal
    except:
        print("False")

success = '832-38-1847'
assert success == checkit(success), "This won't fail this assertion test"
# True

# Should technically fail if formatting match is required
doesNotFail = '832-38-184'
assert doesNotFail == checkit(doesNotFail), "This won't fail this assertion test"
# True

willFail = '832- 23-  1 847'
assert willFail == checkit(willFail), "This one will fail for sure"
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# AssertionError: This one will fail for sure

print("/n(Good job!)")
#
# (Good job!)

答案 1 :(得分:0)

是的,括号是正则表达式中的特殊字符。他们将需要逃脱。但是,这使它变得比原来更加困难。只需使用return value,因为您没有使用任何正则表达式的好处。

str_replace

,或者如果您希望不区分大小写,则使用str_replace('/images/upload/image/201808/thumbnail(3).jpg', 'some_domain_url/images/upload/image/201808/thumbnail(3).jpg', '<img src="/images/upload/image/201808/thumbnail(3).jpg" alt="" />');

i

或...正确的long回曲风:

str_ireplace('/images/upload/image/201808/thumbnail(3).jpg', 'some_domain_url/images/upload/image/201808/thumbnail(3).jpg', '<img src="/images/upload/image/201808/thumbnail(3).jpg" alt="" />');

https://3v4l.org/au5Du