Php script to javascript
I am trying to write something similar in javascript
function Spin($txt){
$test = preg_match_all("#\{(.*?)\}#", $txt, $out);
if (!$test) return $txt;
$toFind = Array();
$toReplace = Array();
foreach($out[0] AS $id => $match){
$choices = explode(”|”, $out[1][$id]);
$toFind[]=$match;
$toReplace[]=trim($c开发者_C百科hoices[rand(0, count($choices)-1)]);
}
return str_replace($toFind, $toReplace, $txt);
But not sure where to start - If there is anybody out there that can help me, please help!
I have a the following as input:
{keyword 1 | keyword 2 | keyword 3} {word 1 | word 2 | word 3} {test 1, test 2, test 3}
The purpose of the script is to combine
- [Keyword 1] [word 1] [test 1]
- [keyword 2] [and word 2] [test 2]
- [keyword 3] [and word 3] [test 3]
I am not sure how to create a array to take the first string { string 1 } break it where ever there is a | then take string 2 { string 2 } and break it at the | and {string 3} and break it at |
and then to combine the strings...
Neither input nor output make sense to me, but well, this should push you into the right direction:
var input = '{keyword 1 | keyword 2 | keyword 3} {word 1 | word 2 | word 3} {test 1, test 2, test 3}';
var matches = input.match(/\{(.*?)\}/ig); // grab stuff in curly braces
var choices = matches[0].replace('{', '') // remove left curly brace
.replace('}', '') // remove right curly brace
.split(' | '); // split into array
choices
will then be an array
['keyword 1', 'keyword 2', 'keyword 3']
You could do the same for words and tests and can then combine these as you see fit.
Look for split method on string
and join method on arrays
Search for Javascript split and Javascript join (separate queries) in google. The w3schools links are quite useful
精彩评论