skip to Main Content

I am trying to split string like below

<?php    
$str = "Q:1) What is PHP?Opensource,cms,framework,webservice,opensource
        Q:2) What is Laravel?Opensource,cms,framework,webservice,framework     
        Q:3) What is WordPress?Opensource,cms,framework,webservice,framwork     
        Q:4) What is Shopify?Opensource,cms,framework,webservice,framwork       
        Q:5) What is Mangento?Opensource,cms,framework,webservice,framwork";    

$ex = explode("Q:",$str);    
echo $ex[0];    

It displays nothing

2

Answers


  1. The 0th index will be empty since th Q: is at the starting location. So start with index 1 onwards

    Your result would be:

    Array
    (
        [0] => 
        [1] => 1) What is PHP?Opensource,cms,framework,webservice,opensource 
        [2] => 2) What is Laravel?Opensource,cms,framework,webservice,framework 
        [3] => 3) What is WordPress?Opensource,cms,framework,webservice,framwork 
        [4] => 4) What is Shopify?Opensource,cms,framework,webservice,framwork 
        [5] => 5) What is Mangento?Opensource,cms,framework,webservice,framwork
    )
    

    Possible workaround:

    You can over come this by applying array_shift:

    array_shift($ex);
    

    This will shift an element off the beginning of your exploded array. Then your array will become:

    Array
    (
        [0] => 1) What is PHP?Opensource,cms,framework,webservice,opensource 
        [1] => 2) What is Laravel?Opensource,cms,framework,webservice,framework 
        [2] => 3) What is WordPress?Opensource,cms,framework,webservice,framwork 
        [3] => 4) What is Shopify?Opensource,cms,framework,webservice,framwork 
        [4] => 5) What is Mangento?Opensource,cms,framework,webservice,framwork
    )
    
    Login or Signup to reply.
  2. That is because the first occurrence of “Q:” is at the very beginning of the string, so the first item in $ex is an empty string. try outputting the second item instead $echo $ex[1];, it should give you

    "1) What is PHP?Opensource,cms,framework,webservice,opensource"

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search