/    Sign up×
Community /Pin to ProfileBookmark

Add Prefix & Suffix values to each string in PHP

Hi,

I need to Add prefix & suffix in some values.

Example :

  • 1. I’m Assigning $value = 1234

  • 2. $prefix = a

  • 3. $Suffix = b

  • 4. The output will be like a1ba2ba3ba4b
  • May I know the procedure or sample coding in PHP?

    to post a comment
    PHP

    2 Comments(s)

    Copy linkTweet thisAlerts:
    @rootFeb 02.2018 — You can use sprintf() to do that [code=php]function wrapit( &$val ){
    $val = sprintf("a%sb", $val);
    }[/code]
    where $val is the number you want your a & b wrapped around.

    Another way would be to convert the $value in to an array with the explode() function, use an array_walk type function to apply to each value the a & b to the stored value and store it back in its original place then use the php implode() function to join the elements back in to an array.
    [code=php]$value = explode("", $value);
    array_walk( &$value, wrapit )
    $value = implode("", $value);
    echo $value;
    [/code]
    (something like that)

    You could use a simple function that uses the sprintf() as demonstrated as the function call and return value without need of assigning other variables or intermediate stages of string manipulation.

    With a bit of tinkering I am sure that you will get this working.
    Copy linkTweet thisAlerts:
    @NogDogFeb 02.2018 — Or...
    [code=php]
    $value = '12345';
    $output = preg_replace('/d/', 'a\0b', $value);
    echo $output;
    [/code]

    Output:
    <i>
    </i>a1ba2ba3ba4ba5b

    _
    ×

    Success!

    Help @priya05 spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.15,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @AriseFacilitySolutions09,
    tipped: article
    amount: 1000 SATS,

    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,
    )...