PHP: Best way to extract text within parenthesis?

后端 未结 8 1474
北海茫月
北海茫月 2020-11-28 06:11

What\'s the best/most efficient way to extract text set between parenthesis? Say I wanted to get the string \"text\" from the string \"ignore everything except this (text)\"

8条回答
  •  日久生厌
    2020-11-28 06:47

    This is a sample code to extract all the text between '[' and ']' and store it 2 separate arrays(ie text inside parentheses in one array and text outside parentheses in another array)

       function extract_text($string)
       {
        $text_outside=array();
        $text_inside=array();
        $t="";
        for($i=0;$i

    Output: extract_text("hello how are you?"); will produce:

    array(1) {
      [0]=>
      string(18) "hello how are you?"
    }
    
    array(0) {
    }
    

    extract_text("hello [http://www.google.com/test.mp3] how are you?"); will produce

    array(2) {
      [0]=>
      string(6) "hello "
      [1]=>
      string(13) " how are you?"
    }
    
    
    array(1) {
      [0]=>
      string(30) "http://www.google.com/test.mp3"
    }
    

提交回复
热议问题