1
votes

The String

$string = '<img width="624" height="36" id="Picture_x0020_3" src="cid:[email protected]" alt="cid:[email protected]">';

The Function

final_content = preg_replace('~src=["]([^"]+)["]~e', "'src=\"data/'.convert_url('$1') . '\"'", $string);
function convert_url($url)
{
    if (preg_match("#^cid?:#", $url)) {
        $url = parse_url($url, PHP_URL_PATH);
    }
    $url2 = substr($url, 0, strpos($url, "@"));
    $url2 = 'data/143-'.$url2;
    return basename($url2);
}

I want to replace the image source from the above mentioned string.

actual pattern :src="cid:[email protected]"

replacement : src="data/image002.png"

The script is working fine in normal PHP code but since I am using CodeIgnitor the calling of the function is not possible in traditional way.

After analyzing a lot of answers found that use preg_replace_callback instead.

Using preg_replace_callback() in CodeIgnitor:

$final_content = preg_replace_callback(
            '~src=["]([^"]+)["]~',
            array($this, 'convert_url'),
            $string);

The Function for CodeIgnitor:

function convert_url($matches)
    {
        if (preg_match("#^cid?:#", $matches[1])) {
            $url = parse_url($matches[1], PHP_URL_PATH);
        }
        $url2 = substr($url, 0, strpos($url, "@"));
        $url3 = 'src=\"data/'.$url2.'\"';
        return basename($url3);
    }

The Function consist of replace the pattern(i.e. 'cid:' with 'data/143-') as well as trimming the content (i.e. after @).


Found the Solution:

Found the solution by changing the preg_replace by preg_replace_callback and used array to call the function.

Also made further changes in the convert_url() since the preg_match("#^cid?:#", $url) was not working in the function.

/e modifier needed to be replaced /i since it was deprecated.

Replace preg_replace with preg_replace_callback

 $final_content = preg_replace_callback(
            '~src=["]([^"]+)["]~i',
            array($this, 'convert_url'),
            $string2);

Remove preg_replace from the function and used a different technique to extract the string.

function convert_url($matches)
    {
        $url = $matches[0];
        $url2 = $this->get_string_between($url,'src="cid:','@');
        $urls = "'$GLOBALS[id]-$url2'";
        $url4 = 'onclick="open_img('.$urls.')" src="data/'.$GLOBALS['id'].'-'.$url2.'"';    
        return strtolower($url4);
    }
    
    function get_string_between($string,$start,$end){
        $string = " ".$string;
        $ini = strpos($string,$start);
        if ($ini == 0) return "";
        $ini += strlen($start);
        $len = strpos($string,$end,$ini) - $ini;
        return substr($string,$ini,$len);
    }
1

1 Answers

0
votes

Where do you write this code? in view page or controller? if you write this code into controller then need to call a function like this $this->convert_url('$1').