Regular Expressions-PHP, how to write regular replacements?

Source: Internet
Author: User
There are strings: ' sdfujer[ema14]xx[emb15],43 you 56^&%^% me [EMC7]] []]

where [EMA14],[EMB15],[EMC7], is the content to be replaced,

' [em ' begins, '] ' ends, the middle consists of letters plus numbers

Replace all of them with this structure,

Should finally get such a string: ' Sdfujerxx , 43 you 56^&%^% me ]] []]

----------Update------------
Downstairs
Wen Lin [1]:http://segmentfault.com/u/wemlin
The answers can be replaced correctly,
Preg_replace ('/\[em ([a-za-z]+\d+) \]/', ' <$1> ', $str);

Reply content:

There are strings: ' sdfujer[ema14]xx[emb15],43 you 56^&%^% me [EMC7]] []]

where [EMA14],[EMB15],[EMC7], is the content to be replaced,

' [em ' begins, '] ' ends, the middle consists of letters plus numbers

Replace all of them with this structure,

Should finally get such a string: ' Sdfujerxx , 43 you 56^&%^% me ]] []]

----------Update------------
Downstairs
Wen Lin [1]:http://segmentfault.com/u/wemlin
The answers can be replaced correctly,
Preg_replace ('/\[em ([a-za-z]+\d+) \]/', ' <$1> ', $str);

LZ please forgive me for a long time useless PHP. Str_replace function or something.

Given that regular expressions are basically common. I answer from the angle of JS, LZ right vote a look at it.

var str = 'sdfUjer[ema14]XX[emb15],43你56^&%^%我[emc7]]]]]]';var regex = /\[em([a-zA-Z]+\d+)\]/g;var result = str.replace(regex , '<$1>');console.log(result === 'sdfUjerXX
  
   
    
   ,43你56^&%^%我
   
    
     
    ]]]]]');
   
    
  
   

$str = "[ema14]XXX[emb15]XXX[emc77]";$pattern = '/\[em([^\]]*)\]/';$resultArr = array();$index = 0;function replaceStr ($arr) {GLOBAL $resultArr;$resultArr[] = "<" . $arr[1] .">";}preg_replace_callback($pattern, 'replaceStr', $str);$str = implode("", $resultArr);
  • Related Article

    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.