Examples of PHP replacing strings based on line numbers

Source: Internet
Author: User

PHP to implement the replacement of content based on the line number, the use of str_replace such a function is not possible, you can break the text into a number based on line breaks, and then facilitate the array to implement the replacement function.

<?php
$url = ' z.txt ';
$content =file_get_contents ($url);
$CONTENTARR =explode ("\ n", $content);
$ikey = 0;
foreach ($contentArr as & $val) {
if (Strpos ($val, ' <!–nextpage–> ')!== false) {
$val = $ikey. ' '. $val;
$ikey + +;
}
}

$content =implode ("\ n", $CONTENTARR);
?>


Add

1. Preg_replace ()

$msg = Preg_replace ("/<style>.+<\/style>/is", "", $msg); -----Delete <style></style> and the middle part
$msg = Preg_replace ("/<[^>]+>/", "", $msg); -----is to delete <> and middle content

I (pcre_caseless)
If you set this modifier, the characters in the pattern will match both the uppercase and lowercase letters.
S (pcre_dotall)
If this modifier is set, the dot meta character (.) in the pattern matches all characters, including line breaks. Without this setting, line breaks are not included. This is equivalent to Perl's/s modifier. Excluding character classes such as [^a] always match newline characters, regardless of whether this modifier is set.


2. Ereg () and eregi ()

Note: the Preg_match () function is usually a faster alternative than ereg ()

Eregi ("<body" ([^>]+) > (. +) </body>, $data, $b)----see if there is a body tag in the $data. If so, assign the parameter to $b[0], and the middle part is assigned a value of $b[1].

BOOL Ereg (string pattern, string string [, array regs])

int eregi (string pattern, string string, array [regs])

Eregi () and Ereg () are similar and use the same. The difference is that ereg () is case-sensitive, and eregi () is not case-insensitive.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.