Link to home
Start Free TrialLog in
Avatar of benners70
benners70

asked on

Convert PHP string replace function to ASP

I'm trying to replicate a PHP string replace function in ASP but I'm having problems completing it. I've attached two working PHP functions that seem to do the same thing, and my attempt at an ASP version. Please run the PHP to see what I'm looking for or view the following for more info http://www.madimmarketing.com/internet-marketing/php-text-spinner/ 
<?php

function spinner1($text) {
    $txt = preg_split("/{|}/", $text);
    foreach($txt as $key => $t){
        if($key%2){
            $spin = preg_split("/\|/", $t);
            $txt[$key] = $spin [mt_rand(1,count($spin)-1)];
        }
    }
    $string = implode("", $txt);
    return $string; 
}  

$test = "The {quick|slow|reasonably paced} {brown|green|blue|pink} {fox|goat|rat|camel} {jumped|walked|hopped} {over|past|under} the {lazy|tired|boring} {dog|cat|stoat}";
echo spinner1($test."<br />");


function spinner2($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 spinner2($s."<br />");
}

echo spinner2('{This|Here} is {some|a {little|wee} bit of} {example|sample} text.');

?>


<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%

function spin(str)
	response.Write(str)
	Set regEx = New RegExp
	regEx.IgnoreCase = true
	regEx.Global = true
	regEx.Pattern = "\{(.*?)\}"
	
	Set Matches = regEx.Execute(str)
	Response.write "# Spin tags:" & Matches.Count & "<br />--------------<br />" 
	For Each Match in Matches
		sMatch = replace(Match.Value,"{","")
		sMatch = replace(sMatch,"}","")
		'response.Write("sMatch = " & sMatch & "<br />")
		a = Split(sMatch,"|")
		aTotal = uBound(a) + 1
		response.Write("words to spin: " & aTotal & "<br />")
		Randomize
		i = Int(Rnd * aTotal)+1
		response.Write("random: " & i & "<br />")
		response.write("output: " & a(i-1) & "<br />--------------<br />")
		
		i = ""
	Next
	spin = str
end function

spin "The {quick|slow|reasonably paced} {brown|green|blue|pink} {fox|goat|rat|camel} {jumped|walked|hopped} {over|past|under} the {lazy|tired|boring} {dog|cat|stoat}"
 
%>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of benners70
benners70

ASKER

Perfect! Thanks very much.
Sure. Glad it worked for you.