break text to sepearte strings in php

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • angelicdevil
    New Member
    • Apr 2009
    • 116

    #1

    break text to sepearte strings in php

    i have a text line " as title: news words:500 body: this is a great day

    now i want the it be broken into such that 3 parts with the variables holding the data as follows

    $title = news
    $words = 500
    $body = this is a great day

    how can i get that? i m trying explode implode but not working here's my code

    Code:
    <?php
    $first = array();
    
    $string = "title: news words:500 body: this is a great day ";
    $sep1 ="title: ";
    $sep2 ="words: ";
    $sep3 ="body: ";
    
    $first[0] = explode($sep2, $string);
    $string0 = implode("",$first[0]);
    $title = $string0;
    echo $title;
    
    ?>
  • JKing
    Recognized Expert Top Contributor
    • Jun 2007
    • 1206

    #2
    Originally posted by angelicdevil
    i have a text line " as title: news words:500 body: this is a great day

    now i want the it be broken into such that 3 parts with the variables holding the data as follows

    $title = news
    $words = 500
    $body = this is a great day

    how can i get that? i m trying explode implode but not working here's my code

    Code:
    <?php
    $first = array();
    
    $string = "title: news words:500 body: this is a great day ";
    $sep1 ="title: ";
    $sep2 ="words: ";
    $sep3 ="body: ";
    
    $first[0] = explode($sep2, $string);
    $string0 = implode("",$first[0]);
    $title = $string0;
    echo $title;
    
    ?>
    Code:
    <?php
    $first = array();
     
    $string = "title: news words: 500 body: this is a great day ";
    $sep1 ="title: ";
    $sep2 ="words: ";
    $sep3 ="body: ";
     
    $body = strstr($string, $sep3);
    
    
    $string = str_replace ($body ,"", $string);
    $body = str_replace ($sep3, "", $body);
    $title = strstr($string, $sep2, true);
    $string= str_replace ($title, "" , $string);
    $title = str_replace ($sep1, "", $title);
    $words= str_replace($sep2, "", $string);
    
    echo $title . "<br />";
    echo $body . "<br />";
    echo $words;
    
    ?>

    Comment

    • HaLo2FrEeEk
      Contributor
      • Feb 2007
      • 404

      #3
      Instead of actually including the words title:, words:, body:, just leave them out and use a specific separator between your items, so if your title is "news", words is 500 and body is "hello world", try this:

      Code:
      $string = "News|500|Hello World!";
      
      $split = explode("|", $string);
      Now your $split variable is an array with these values:

      $split[0] = News
      $split[1] = 500
      $split[2] = Hello World

      Use them as you would.

      Comment

      • angelicdevil
        New Member
        • Apr 2009
        • 116

        #4
        where m i wrong in this code?

        thanx it worked

        Comment

        Working...