The PHP keyword replaces only once the implementation function _php technique

Source: Internet
Author: User

There's nothing to say about replacing a keyword with a bulk replacement, but what you need here is that each keyword needs to be replaced only once. Check the PHP related function document, found that PHP itself is not a function to achieve this function, so have to solve their own. summed up several feasible methods, small remember!
(1) using the Preg_replace function to implement this function, because the Preg_replace function itself can be implemented to control the number of replacements, so the first thought of him, the specific implementation of the following methods:

Can be implemented to control the number of substitutions, not only to replace only once, such as $limit 2 when a word appears a lot of eating only 2 times,-1 to replace all. $search and $replace can be either strings or arrays, but must correspond to 
function Str_replace_limit ($search, $replace, $content, $limit =-1) { 
  if ( Is_array ($search)) { 
    foreach ($search as $k => $v) { 
      $search [$k]=]. Preg_quote ($search [$k], ""). ' `'; 
    } 
  } else{ 
    $search = '. Preg_quote ($search, '). `'; 
  } 
  Remove the picture description 
  $content =preg_replace ("/alt= ([^ >]+)/is", $content); 
  Return Preg_replace ($search, $replace, $content, $limit); 
 

(2) using the Substr_replace function, but only one replacement can be implemented here

First find the location of the keyword and then use Substr_replace (System function) to replace the operation 
function Str_replace_once ($search, $replace, $content) { 
  // Remove the picture description 
  $content =preg_replace ("/alt= ([^ >]+)/is", $content); 
  $pos =strpos ($content, $search); 
  if ($pos ===false) {return 
    $haystack; 
  } 
  Return Substr_replace ($content, $replace, $pos, strlen ($search)); 

' Above is the PHP only replaces once and controls the replacement number The realization function, hoped that has the help to everybody's study.

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.