Replacer   A
last analyzed

Complexity

Total Complexity 2

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 43
rs 10
wmc 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getModifiedRegexPattern() 0 3 1
A replace() 0 3 1
1
<?php
2
3
namespace Matecat\Finder\Helper;
4
5
class Replacer
6
{
7
    /**
8
     * This method replaces content avoiding to replace html content.
9
     *
10
     * Example:
11
     * $haystack = "Beauty -> 2 Anti-Akne Gesichtsreiniger Schlankmacher <g id=\"2\">XXX</g>";
12
     * $needle = 2;
13
     * $replacement = "test";
14
     *
15
     * $expected = "Beauty -> test Anti-Akne Gesichtsreiniger Schlankmacher <g id=\"2\">XXX</g>";
16
     *
17
     * @param string $pattern
18
     * @param string $replacement
19
     * @param string $haystack
20
     *
21
     * @return string|string[]
22
     */
23
    public static function replace($pattern, $replacement, $haystack)
24
    {
25
        return preg_replace(self::getModifiedRegexPattern($pattern), $replacement, $haystack);
26
    }
27
28
    /**
29
     * Modifies regex pattern for avoiding replacement of html content
30
     *
31
     * This function appends to the original $pattern a new optional regex.
32
     *
33
     * Example:
34
     *
35
     * /ciao/iu
36
     *
37
     * is converted to:
38
     *
39
     * /(\|\|\|\||<.*?>|%{.*?})(*SKIP)(*FAIL)|ciao/iu
40
     *
41
     * @param string $pattern
42
     *
43
     * @return string
44
     */
45
    private static function getModifiedRegexPattern($pattern)
46
    {
47
        return '/(\|\|\|\||<.*?>|&lt;.*?&gt;|%{.*?})(*SKIP)(*FAIL)|'. ltrim($pattern, $pattern[0]);
48
    }
49
}
50