0

Hi I am using this function in PHP to create some spun content (using spintax). However, if the spintax contains $ (dollar signs) they are removed in the output.

    function spintext($s){

        preg_match('#\{(.+?)\}#is',$s,$m);
        if(empty($m)) return $s;

        $t = $m[1];

        if(strpos($t,'{')!==false){
            $t = substr($t, strrpos($t,'{') + 1);
        }

        $parts = explode("|", $t);
        $s = preg_replace("+\{".preg_quote($t)."\}+is", $parts[array_rand($parts)], $s, 1);

        return spintext($s);
    }

$out = spintext("Spinning a dollar sign: {$200|$400|$300}");
echo $out;

Results in:

Spinning a dollar sign: 0

Can anyone advise why this might be? Also, can you see any areas where the efficiency of this code might be improved to speed up the spin process and reduce memory usage?

Machavity
  • 30,841
  • 27
  • 92
  • 100
Tao Schencks
  • 57
  • 1
  • 7
  • dolar sign is part of variables, if you want to keep it on the output, you can either use single quotes ' or escape before $ sign \$ – Richard May 16 '16 at 12:57

1 Answers1

3

as you are using double quotes around your string:

$out = spintext("Spinning a dollar sign: {$200|$400|$300}");

PHP will parse and try to replace them with that variables contents before outputting the string.

(Also, this should throw an error as variables should never start with a number.)

You need to either use single quotes (literal)

$out = spintext('Spinning a dollar sign: {$200|$400|$300}');

or escape the dollar signs \$.

$out = spintext("Spinning a dollar sign: {\$200|\$400|\$300}");
DevDonkey
  • 4,835
  • 2
  • 27
  • 41