Search code examples
phparraysstringsubstrstrpos

Combine php strings with substr and strpos into one string


Not sure if this has been asked but what's the best way to combine three strings into one string. I tried adding an array but it didn't work.

My strings are: $linktitle = get_the_title(); $linkt = substr($linktitle, 0, strpos($linktitle, ' —')); $linkt2 = substr($linktitle, 0, strpos($linktitle, ' –')); $linkt3 = substr($linktitle, 0, strpos($linktitle, ' |'));

Example $linktitle outputs:

Facebook Creates YouTube-Like Video Feature Inside Facebook | Re/code WNYC to Open New Podcast Division – The New York Times

My attempt at combination didn't work: $linkall = substr($linktitle, 0, strpos($linktitle, array(' —', –',' |')));

What I would like to accomplish is combine , –, and | into an array like in the above example (if possible).


Solution

  • How about using implode() on the array containing your strings?

    Something like

    $pieces = array($string1, $string2, $string3);
    $result = implode('', $pieces);
    

    In your case perhaps this makes more sense:

    $pieces=array();
    $pieces[] = substr($linktitle, 0, strpos($linktitle, ' —'));
    $pieces[] = substr($linktitle, 0, strpos($linktitle, ' –'));
    $pieces[] = substr($linktitle, 0, strpos($linktitle, ' |'));
    $result = implode('', $pieces);
    echo $result;