Adding a String Within a String in PHP
I have a basic string question in PHP.
Let's say I have a variable $story
:
开发者_StackOverflow社区$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
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:
- http://www.php.net/manual/en/language.types.string.php
- http://www.php.net/manual/en/function.sprintf.php
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
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";
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);
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);
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);
精彩评论