Convert PHP string replace function to ASP

Posted on 2011-10-28
Last Modified: 2012-05-12
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

function spinner1($text) {
    $txt = preg_split("/{|}/", $text);
    foreach($txt as $key => $t){
            $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){
	if(empty($m)) return $s;

	$t = $m[1];

		$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.');



function spin(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 />")
		i = Int(Rnd * aTotal)+1
		response.Write("random: " & i & "<br />")
		response.write("output: " & a(i-1) & "<br />--------------<br />")
		i = ""
	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

Question by:benners70
    LVL 74

    Accepted Solution

    Try this:

    Spinner 1
    Function spinner1(text)
            Const placeholder = "%%%##%%%"
            Set regex = New RegExp
            With regex
                    .Pattern = "{|}"
                    .Global = True
                    fixed = .Replace(text, placeholder)
            End With
            txt = Split(fixed, placeholder)
            For key = 0 To UBound(txt)
                    If key Mod 2 <> 0 Then
                            spin = Split(txt(key), "|")
                            idx = Int((UBound(spin) + 1)*Rnd(Timer))
                            txt(key) = spin(idx)
                    End If
            str = ""
            For Each value In txt
                    str = str & value
            spinner1 = str
    End Function

    Open in new window

    Spinner 2
    Function spinner2(s)
            Set regex = New RegExp
            With regex
                    .Pattern = "\{([^}]*)\}"
                    Set m = .Execute(s)
            End With
            If m Is Nothing Then
                    spinner2 = s
                    Exit Function
            ElseIf m.Count = 0 Then
                    spinner2 = s
                    Exit Function        
            End If
            t = m(0).SubMatches(0)
            If InStr(1, t, "{") > 0 Then
                    t = Mid(t, InStr(1, t, "{") + 1)
            End If
            parts = Split(t, "|")
            ' Substitute for preg_quote
            With regex
                    .Pattern = "([-^${}\[\]().?\\*+|])"
                    .Global = True
                    t = .Replace(t, "\$1")
            End With
            With regex
                    .Global = False
                    .Pattern = "\{" & t & "\}"
                    idx = Int((UBound(parts) + 1)*Rnd(Timer))
                    s = .Replace(s, parts(idx))
            End With
            spinner2 = spinner2(s & "<br />")
    End Function

    Open in new window


    Author Comment

    Perfect! Thanks very much.
    LVL 74

    Expert Comment

    by:käµfm³d 👽
    Sure. Glad it worked for you.

    Featured Post

    How to improve team productivity

    Quip adds documents, spreadsheets, and tasklists to your Slack experience
    - Elevate ideas to Quip docs
    - Share Quip docs in Slack
    - Get notified of changes to your docs
    - Available on iOS/Android/Desktop/Web
    - Online/Offline

    Join & Write a Comment

    I was asked about the differences between classic ASP and ASP.NET, so let me put them down here, for reference: Let's make the introductions... Classic ASP was launched by Microsoft in 1998 and dynamically generate web pages upon user interact…
    Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
    This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
    The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

    728 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now