質問

What I'm trying to do is add forward slash to the beginning and end of a string of text if the first and last character of the string is not /.

In my script I have:

if(!reFind('\/\S\/', myString){
    myString = '/' & arrayToList(listToArray(myString, '/\'), '/') & '/');
}

I want to run a ReReplace instead of listing to an array and then adding the slashes in.

役に立ちましたか?

解決

Using array to list and list to array could possibly remove inner slashes, so you don't want to do that. Instead, replace leading and trailing slashes with a regex.

<cfscript>
    string1 = "foobar";
    string2 = "/foobar/";
    string3 = "foo/bar";
    string4 = "/foo/bar/";

    function addSlashes (str) {
        return "/" & reReplace(str,"^/|/$","","all") & "/";
    }

    writeDump(addSlashes(string1));
    writeDump(addSlashes(string2));
    writeDump(addSlashes(string3));
    writeDump(addSlashes(string4));
</cfscript>

you can paste the above into http://www.trycf.com

他のヒント

You should just be able to replace ^/?(.*?)/?$ with /\1/.

See a visual explanation at http://www.regexper.com/

Note the pattern I use @ www.regexper.com is slightly different as I need to escape the / for a JS pattern; not so with CFML ones.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top