一.原因:
做一個PHP的測試載入器,這樣可以直接測試正則。以後還可以發展這一工具。
二.代碼:
index.php
<!DOCTYPE html><html><head><meta charset="UTF-8"><link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css"><link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"><script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script><script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script></head><body><div style="padding: 30px 300px 10px;" id = "content"> <h2>Regex測試</h2> <br /> <form class="bs-example bs-example-form" role="form"> <div class="row"> <div class="col-lg-9"> <form role="form"> <div class="form-group"> <label for="name">源文本</label> <textarea class="form-control" rows="9" id = "textContent"></textarea> </div> </form> </div> </div> <div class="row"> <div class="col-lg-9"> <label for="name">Regex</label> <div class="input-group"> <input type="text" class="form-control" id = "regularExpression" > <span class="input-group-btn"> <button class="btn btn-default" type="button" onclick = "detectionRegularity()" > 檢測 </button> </span> </div><!-- /input-group --> </div><!-- /.col-lg-6 --> </div><!-- /.row --> <br /> <div class="row"> <div class="col-lg-9"> <form role="form"> <div class="form-group"> <label for="name">正則結果</label> <textarea class="form-control" rows="3" id = "regexResult"></textarea> </div> </form> </div> </div> </form></div><script> //檢測正則 function detectionRegularity(){ var regularExpression = $("#regularExpression").val(); var textContent = $("#textContent").val(); $.ajax({ url: 'testRegular.php', type:'post', dataType:'json', data:{ 'regularExpression':regularExpression, 'textContent':textContent }, success:function(data){ var showContent = ""; for(var eachItem in data){ showContent += data[eachItem] + "\n"; } $("#regexResult").html(showContent); }, error:function(){ $("#regexResult").html("無結果"); } }); }</script></body></html>
testRegular.php
<?php$regularExpression = $_POST['regularExpression'];$textContent = $_POST['textContent'];if (preg_match_all ($regularExpression, $textContent, $result)){ if ($result[2]){ $regexResult = $result[2]; echo json_encode($regexResult); }}