国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home php教程 php手冊 PHP HTML代碼串截取代碼

PHP HTML代碼串截取代碼

Jun 13, 2016 pm 12:25 PM
AAA class div html php code intercept data yes

而且給的數(shù)據(jù)是HTML代碼串,比如這樣:


截取的時候是要截取 div 標(biāo)簽內(nèi)部的東西,而且要保留HTML標(biāo)簽,只是對其中的文字做處理。比如我可能只是截取到“李四”的“李”字,但是如果就這樣放到前端的話,“李四”前面的 a 標(biāo)簽是沒有閉合的,所以截取之后要保證HTML的語法正確。
這個問題確實(shí)不太好搞,讓我郁悶了兩天。請注意,這只是一個字符串,只不過內(nèi)容是HTML代碼,是沒有什么DOM的。如果是在前端處理就好辦了,直接DOM獲取,然后對里面的節(jié)點(diǎn)進(jìn)行處理,最后把innerHTML 之類的東西輸出就搞定了?,F(xiàn)在可不行了,得換個思路。同事的思路是這樣的:
遍歷字符串的每一個字符。設(shè)置一個標(biāo)記,碰到標(biāo)簽開始的標(biāo)記之后再開始計(jì)數(shù)。對標(biāo)簽內(nèi)部的字符串處理的時候,還要先判斷當(dāng)前字符的編碼是不是可能是中文,一般來說PHP中 UTF-8 編碼的中文字符的長度都是3,所以如果碰到是中文字符編碼,就要跳過兩個不記數(shù)……說到這里我自己頭已經(jīng)開始大了。個人認(rèn)為這種方法很不爽,首先這種精致的邏輯不太容易控制,而且 UFT-8 編碼下中文產(chǎn)生的長度有可能是3個或4個 所以代碼的嚴(yán)密性值得懷疑。
我個人的思路是,用 Tidy 來搞(具體用法請看PHP手冊吧)。昨天研究了一下那個 Tidy ,發(fā)現(xiàn)這個東西還是挺好用的。首先,把這個字符串轉(zhuǎn)換成 Tidy 對象,這樣:
$tidy = tidy_parse_string($str, array(), ‘utf8′); // 最后一個是設(shè)置編碼的,注意,這里是utf8 ,不是utf-8,沒有中間那個連線。
然后獲取$tidy中的 body(因?yàn)檗D(zhuǎn)換之后$tidy會自動加上等標(biāo)簽):
$body = tidy_get_body($tidy);
這個時候你可以用 var_dump 看一些 $body 的結(jié)構(gòu),會發(fā)現(xiàn)它把每個標(biāo)簽都變成了一個對應(yīng)的對象,里面有相應(yīng)的屬性。舉例來說,比如 sdf ,這么一條語句對應(yīng)的一些屬性有:
name=>”a”
value => “sdf
child=> array{[0]=>一個文本節(jié)點(diǎn)對象,value是 sdf}
attribute=array{”href”=>”#”}
…..其他屬性
可以看到,我們其實(shí)是可以單獨(dú)去處理 a 標(biāo)簽對應(yīng)節(jié)點(diǎn)下面的文字節(jié)點(diǎn)的值的,那樣就不會破壞任何HTML完整性。原來我以為改變 a 標(biāo)簽中文字節(jié)點(diǎn)的值之后, a 標(biāo)簽的value也會跟著改變,那樣我直接返回a標(biāo)簽對應(yīng)節(jié)點(diǎn)的value就OK了,沒想到不是那個樣子,哎,所以處理過其中的文字之后還是要自己拼出新的HTML。
知道了Tidy對象的結(jié)構(gòu)之后,一切就好辦了,只要遍歷所有的節(jié)點(diǎn),對于本需求來說,就是找到那個 div 標(biāo)簽,然后開始處理里面的節(jié)點(diǎn)。代碼如下:
if(mb_strwidth($subchild->value, ‘utf-8′) >= $len)
{
$subchild->value = mb_strimwidth($subchild->value, 0, $len, ‘…', ‘utf-8′);
$trimed_str .= $subchild->value;
break;
}
else
{
$trimed_str .= $subchild->value;
$len = $len - mb_strwidth($subchild->value, ‘utf-8′);
}
里面的$subchild 就是一個子節(jié)點(diǎn)。注意,這里使用了 mb_strwidth 來獲取字符串長度。嚴(yán)重推薦一下這個 mb_strwidth,很好用,它會把中文當(dāng)作兩個字符長度處理,正好符合這里的需求!而且截取字符串的時候用到了 mb_strimwidth,這個函數(shù)也會把中文當(dāng)作兩個字符長度處理,mb_ 開頭的函數(shù)真是好用啊。
具體代碼我就不寫出來了,因?yàn)槭轻槍σ粋€需求寫的,沒做成通用的形式。哪天我有時間做成通用的再發(fā)布一下。
另外,可惜FireFox不支持 text-overflow 屬性,不然也不用后臺那么辛苦地去截?cái)嗔?。如果大家有更好的方法,歡迎提出!不勝感激。
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use php exit function? How to use php exit function? Jul 03, 2025 am 02:15 AM

exit() is a function in PHP that is used to terminate script execution immediately. Common uses include: 1. Terminate the script in advance when an exception is detected, such as the file does not exist or verification fails; 2. Output intermediate results during debugging and stop execution; 3. Call exit() after redirecting in conjunction with header() to prevent subsequent code execution; In addition, exit() can accept string parameters as output content or integers as status code, and its alias is die().

How to combine two php arrays unique values? How to combine two php arrays unique values? Jul 02, 2025 pm 05:18 PM

To merge two PHP arrays and keep unique values, there are two main methods. 1. For index arrays or only deduplication, use array_merge and array_unique combinations: first merge array_merge($array1,$array2) and then use array_unique() to deduplicate them to finally get a new array containing all unique values; 2. For associative arrays and want to retain key-value pairs in the first array, use the operator: $result=$array1 $array2, which will ensure that the keys in the first array will not be overwritten by the second array. These two methods are applicable to different scenarios, depending on whether the key name is retained or only the focus is on

Applying Semantic Structure with article, section, and aside in HTML Applying Semantic Structure with article, section, and aside in HTML Jul 05, 2025 am 02:03 AM

The rational use of semantic tags in HTML can improve page structure clarity, accessibility and SEO effects. 1. Used for independent content blocks, such as blog posts or comments, it must be self-contained; 2. Used for classification related content, usually including titles, and is suitable for different modules of the page; 3. Used for auxiliary information related to the main content but not core, such as sidebar recommendations or author profiles. In actual development, labels should be combined and other, avoid excessive nesting, keep the structure simple, and verify the rationality of the structure through developer tools.

What is the loading='lazy' one of the html attributes and how does it improve page performance? What is the loading='lazy' one of the html attributes and how does it improve page performance? Jul 01, 2025 am 01:33 AM

loading="lazy" is an HTML attribute for and which enables the browser's native lazy loading function to improve page performance. 1. It delays loading non-first-screen resources, reduces initial loading time, saves bandwidth and server requests; 2. It is suitable for large amounts of pictures or embedded content in long pages; 3. It is not suitable for first-screen images, small icons, or lazy loading using JavaScript; 4. It is necessary to cooperate with optimization measures such as setting sizes and compressing files to avoid layout offsets and ensure compatibility. When using it, you should test the scrolling experience and weigh the user experience.

php raw post data php php raw post data php Jul 02, 2025 pm 04:51 PM

The way to process raw POST data in PHP is to use $rawData=file_get_contents('php://input'), which is suitable for receiving JSON, XML, or other custom format data. 1.php://input is a read-only stream, which is only valid in POST requests; 2. Common problems include server configuration or middleware reading input streams, which makes it impossible to obtain data; 3. Application scenarios include receiving front-end fetch requests, third-party service callbacks, and building RESTfulAPIs; 4. The difference from $_POST is that $_POST automatically parses standard form data, while the original data is suitable for non-standard formats and allows manual parsing; 5. Ordinary HTM

How to create an array in php? How to create an array in php? Jul 02, 2025 pm 05:01 PM

There are two ways to create an array in PHP: use the array() function or use brackets []. 1. Using the array() function is a traditional way, with good compatibility. Define index arrays such as $fruits=array("apple","banana","orange"), and associative arrays such as $user=array("name"=>"John","age"=>25); 2. Using [] is a simpler way to support since PHP5.4, such as $color

Windows search bar not typing Windows search bar not typing Jul 02, 2025 am 10:55 AM

When the Windows search bar cannot enter text, common solutions are: 1. Restart the Explorer or computer, open the Task Manager to restart the "Windows Explorer" process, or restart the device directly; 2. Switch or uninstall the input method, try to use the English input method or Microsoft's own input method to eliminate third-party input method conflicts; 3. Run the system file check tool, execute the sfc/scannow command in the command prompt to repair the system files; 4. Reset or rebuild the search index, and rebuild it through the "Index Options" in the "Control Panel". Usually, we start with simple steps first, and most problems can be solved step by step.

What are best practices for writing valid and well-formed HTML code? What are best practices for writing valid and well-formed HTML code? Jul 01, 2025 am 01:32 AM

When writing legal and neat HTML, you need to pay attention to clear structure, correct semantics and standardized format. 1. Use the correct document type declaration to ensure that the browser parses according to the HTML5 standard; 2. Keep the tag closed and reasonably nested to avoid forgetting closed or wrong nesting elements; 3. Use semantic tags such as, etc. to improve accessibility and SEO; 4. The attribute value is always wrapped in quotes, and single or double quotes are used uniformly. Boolean attributes only need to exist, and the class name should be meaningful and avoid redundant attributes.

See all articles