การใช้ฟังก์ชัน ที่จะแนะนำต่อไปนี้ สามารถนำไปประยุกต์ใช้กับการจัดรูปแบบ url ของ ลิ้งค์ link ให้กับข้อมูล
ที่ทำการดึงจากฐานข้อมูล เฃ่น ลิ้งค์หรือ url ที่โพสในเว็บบอร์ด บทความ ข่าว หรืออื่นๆ หากมีไอเดีย ที่หลากหลาย สามารถปรับเพิ่มเติม ให้ใช้งานอย่างมีประสิทธิภาพได้
ตัวอย่าง
https://www.ninenik.com/demo/link_replace_full.php
โค้ตตัวอย่างด้านล่าง เป็นตัวอย่างการใช้งาน เพื่อประยุกต์ กับการปรับ url แทนการใช้ jQuery จากบทความ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | <?php $dataHTML =<<<BOF <div class = "iTopicQUE_R" > <p>แนะนำ 2 เว็บด้านล่าง ทำ tag cloud จากฐานข้อมูล จะเป็นเว็บที่ 2<br /> http: //www.thaicreate.com/community/tag-cloud.html</a><br /> http: //www.narongrit.net/download-readdownload-id63.html</a></p> <a href= "www.google.com" >Google</a><br /> <a href= 'code.google.com' >Code Goodle</a><br /> <a Href= "#" >anchor</a><br /> <a href= "mailto:ninenik@gmail.com" >mail to</a><br /> <a href= "?data=3" >Some Argument</a><br /> <a href=index.html?data=3>Some Argument 2</a><br /> <a href= "www.ninenik.com" >Ninenik.com</a><br /> </div> BOF; echo "<strong>ตัวอย่าง ส่วนของเนื้อหาที่ยังไม่ได้จัดรูปแบบ ของ ลิ้งค์</strong><br/>" ; echo $dataHTML ; echo "<hr>" ; echo "<strong>ตัวอย่าง ส่วนของเนื้อหาที่ จัดรูปแบบ ของ ลิ้งค์ แล้ว</strong><br/>" ; function adjustLink( $matches ){ $siteDomain = "www.ninenik.com" ; // domain เว็บที่ไม่ต้องกำหนดรูปแบบ ลิ้งค์ใหม่ $matchesData = strtolower ( $matches [0]); $dom = new DOMDocument; libxml_use_internal_errors(true); $dom ->loadHTML( $matchesData . "</a>" ); libxml_use_internal_errors(false); $xpath = new DOMXPath( $dom ); $LinkTag = $xpath ->query( '//a[@href]' ); foreach ( $LinkTag as $val ) { $matchesData =trim( $val ->getAttribute( 'href' )); } if (preg_match( "/^(mailto:)|^(#)|^(\?)/" , $matchesData )){ return "<a href=\"$matchesData\">" ; } if (!preg_match( "@^(https?://)@" , $matchesData )){ if (preg_match( "/$siteDomain/i" , $matchesData )){ } else { } } else { if (preg_match( "/$siteDomain/i" , $matchesData )){ return "<a href=\"$matchesData\">" ; } else { return "<a href=\"" . $linkMody . $matchesData . "\">" ; } } } ?> |
การใช้งาน
1 2 3 4 5 6 7 | <?php // การใช้งาน // $dataHTML คือ ข้อมูล html สามารถส่งค่าตัวแปรมาได้ // adjustLink คือชื่อฟังก์ชัน ที่ใช้สำหรับจัดรูปแบบของ url ลิ้งค์ link $pathen = "/<a[^<]+?>/" ; echo preg_replace_callback( $pathen , "adjustLink" , $dataHTML ); ?> |