1

I am adding characters to a string of words and not quite getting the result I need.

I have a string like this: $string = "word word word word"

The output I need is: 'word'+'word'+'word'+'word'

What I am getting is: word+word+word+word+

Here is the function I am using:

$str = "word word word word";  
$str = implode("+", explode(" ", $str))."+";
echo $str;
1
  • 2
    what do you think this bit at the end is doing ."+"; ?? Commented Sep 22, 2014 at 3:25

2 Answers 2

3

Just concatenate single qoutes on both sides:

$str = "'".implode("'+'", explode(" ", $str))."'";
       ^^           ^ ^                        ^
// outside quotes   inside quotes           outside qoutes

Or like this:

$str = "'".str_replace(' ', "'+'", $str)."'";
Sign up to request clarification or add additional context in comments.

5 Comments

My test works great, but when I include it as part of my form's post function prior to Inserting into the database the whole form post will not insert into mysql database.
@Jason i was wondering whats the context of this, how are you using it. you should have posted it earlier
probably the quotes not being escaped properly in the querry
@Ghost please see context above. Thanks!
@Jason use mysql_real_escape_string() in the end before using it in the query
3

Implode and concatenate the surrounding apostrophes like this:

$str = "word word word word";  
$str = "'" . implode("'+'", explode(" ", $str)) . "'";
echo $str;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.