Replacer::replace()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 3
dl 0
loc 3
rs 10
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