0

I have a basic string question in PHP.

Let's say I have a variable $story:

$story = 'this story is titled and it is really good';

How would I go about adding a string after 'titled' and before 'and'? If I had the title in a another variable, let say

$title = 'candy';

What function or method could I use to do this?

$story = 'this story is titled and it is really good';
$title = 'candy';
// do something
var_dump($story === 'this story is titled candy and it is really good'); // TRUE
1

5 Answers 5

6

There are a few options.

$title = 'candy';
$story = 'this story is titled '.$title.' and it is really good';
$story = "this story is titled $title and it is really good";
$story = sprintf('this story is titled %s and it is really good', $title);

See:

If you are using php with html and want to print the string (outside of php tags)

this story is titled <?php echo $title ?> and it is really good
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the simple explanation, i forgot to mention that i wanted to do it without creating a new variable. thanks for the help everyone!
0

You just need to use double quotes and put the variable inside the string, like so:

$title = 'candy';
$story = "this story is titled $title and it is really good";

3 Comments

Also $story = 'this story is titled ' . $title . ' and it is really good';
Hmm, I added that part to my comment before I saw this - now it has been removed?
this solution assumes that $title is defined before $story, which may not always be the case.
0

I'd recommend using a placeholder in your original string, and then replacing the placeholder with your title.

So, amend your code to be like this:

$story = "this story is titled {TITLE} and it is really good";

Then, you can use str_replace to replace your placeholder with the actual title, like this:

$newStory = str_replace("{TITLE}", $title, $story);

Comments

0

The easy way would be:

$story="this story is titled $title and it is really good".

If you're asking how to find where to insert, you could do something like this:

$i=stripos($story," and");
$story=substr($story,0,$i)." ".$title.substr($story,$i);

The third was is to place a token that's unlikely to appear in the text like ||TITLE||. Search for that and replace it with the title text like:

$i=stripos($story,"||TITLE||");
$story=substr($story,0,$i).$title.substr($story,$i+9);

Comments

0

Take advantage of your friend string interpolation (as GreenWevDev said).

Or if you need to replace the word title with a string, and only on its own, you can with regex.

$story = preg_replace('/\btitle\b/', $title, $story);

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.