如何将正则表达式数据转换为全局字符串php

I have a function like below

function addMinus($string){

  $output = str_replace("%20", "-", $string);
  $output = str_replace(" ", "-", $output);

  return $output;

}

I need to use function that given above in the following function

function addgsk($string){

    $regex = '~\(gsk:(.*?)\)~six';
    $link = "$1";
    $link = addMinus($link);
    $output = preg_replace($regex, "<a href='$link'>(gsk:$1)</a>", $string);

   return $output;

}

But my problem is that $link = addMinus($link); do not work. The spaces do not replaced by "-". I think it is because of the data from regex.

Note: I do not get any error but the function (addMinus) do not work.

It might be a problem with the regex, but we'd need to know the pattern of what you actually want to replace first.

Either way, right now $link has a value of $1 assigned to it before the regex occurs. Tell me if this helps at all (and if not, we can figure it out from there):

function addgsk($string){
    $regex = '~\(gsk:(.*?)\)~six';
    $link = addMinus($string);
    $output = preg_replace($regex, '<a href="' . $link . '">(gsk:$1)</a>', $string);
    return $output;
}

This doesn't work because you can't use a reference like $1 as a variable which is only defined inside the replacement pattern of preg_replace or preg_replace_callback. When you write $link = "$1"; the reference $1 is not defined, and when you call addMinus, the poor function try to find spaces in this literal string: "$1"

A way to solve your problem is to use preg_replace_callback that allows to use a function before the replacement. See the official documentation: http://php.net/manual/en/function.preg-replace-callback.php

I don't know which data your want,

function add_minus_gsk($string) {

    return preg_replace_callback(
        '@\(gsk:([^)]++)\)@i',
        function ($matches) {
            return sprintf(
                '<a href="%s">(gsk:%s)</a>',
                str_replace(array('%20', ' '), '-', $matches[1]),
                $matches[1]
            );
        },
        $string
    );

}

or

function add_minus_gsk($string) {

    return preg_replace(
        '@\(gsk:([^)]++)\)@i',
        '<a href="$1">(gsk:$1)</a>',
        str_replace(array('%20', ' '), '-', $string)
    );

}

Try both.