计算<;pre>;使用php或jquery标记


Count words in <pre> tag using php or jquery

我想计算以下语句中的单词:

<pre id="output" class="output">["PHP","Python"]</pre>

然后,我需要通过POST(提交按钮)将每个单词分配给一个PHP变量

当单词在[","]标记中时,我不知道如何在PHP或JQuery中计数?我有一个插件(无法编辑代码),它按照描述填充预标记。

提前感谢

Simon

html:

<pre id="output" class="output">["PHP","Python"]</pre>
<form method="post" target="#" id="myForm">
    <input type="submit"/>
</form>
<textarea id="result" style="width:400px; height:200px;">
</textarea>

jQuery:

//get rid of the brackets and split the vars with the comma as a delimiter
var varsArray= $("#output").html().split('[')[1].split(']')[0].split(',');
//count the elements:
var total = $(varsArray).length;
$(varsArray).each(function(idx,value){
    // the each function provides id and value, you use those to create a hidden field
    // in your form and set its name using the id, and value using the value 
    $("#myForm").append('<input type="hidden" name="var'+idx+'" value='+value+'>'n'r');
});
//print the new form's content into the text area just to see what it will look like
$("#result").val($("#myForm").html());

下面是jsfiddle中的一个例子,我希望它能有所帮助:

http://jsfiddle.net/TheBanana/AD8x9/

首先你需要获得pre-so:的内容

jQuery示例:

var contents = $("#output").html();
//now you could need to remove "[" and "]":
contents = contents.replace("[","").replace("]","");
var elements = contents.split(",");
//now you will have to check the length of "elements"
var count = elements.length;