phpstringsubstringprefix

Add substring at beginning of string if doesn't exist


I want to add a substring (text) at beginning of string only if this string doesn't have already this text at beginning.

Example:

// let's say I want to add "Has" at beginning (if doesn't exist)

$string_1 = "AnaHasSomeApples"; // we need to add
$string_2 = "HsSomeApples"; // we need to add
$string_3 = "HasApplesAlready"; // already exists at the beginning

I tried this:

$string = (strpos($string, 'Has') === false ? 'Has' : '') . $string;

I know is not hard to do that.

I am more interested in finding the fastest (according to time, not lines of code) possible way.


Solution

  • I am checking if Has is not at position 0 then prepend 'Has' with existing string
    You can use ternary operator to achieve this,

    $string_1 = "AnaHasSomeApples"; // we need to add
    $string_2 = "HsSomeApples"; // we need to add
    $string_3 = "HasApplesAlready"; // already exists at the beginning
    
    echo "string_1: ". (strpos($string_1,"Has") !== 0 ? "Has".$string_1: $string_1)."\n";
    echo "string_2: ". (strpos($string_2,"Has") !== 0 ? "Has".$string_2: $string_2)."\n";
    echo "string_3: ". (strpos($string_3,"Has") !== 0 ? "Has".$string_3: $string_3)."\n";
    

    Output

    string_1: HasAnaHasSomeApples
    string_2: HasHsSomeApples
    string_3: HasApplesAlready
    

    Demo.