Reputation: 528
Wondering if anyone can help me out here, is there any relatively simple way of inserting some tags with a given string after a certain amount of words...
for example, taking:
$string = 'Helping customers to do something everyday';
and inserting a after every third word so the output would be
Helping customers to </span><span> do something everyday
I'm guessing the use of a regular expression of some sort, but they are not my strong point or perhaps within a for loop?
/////////////////////////////
UPDATE:
Cheers for the help guys:
I had a brainwave and come up with this function, which done exactly what I needed:
function insert_tags ( $string )
{
$string = explode ( " ", $string );
$count = 0;
$result = '';
foreach ( $string as $s )
{
if ( $count == 3 )
{
$result .= '</span><span>' . $s . ' ';
$count = 1;
}
else
{
$result .= $s . ' ';
}
$count++;
}
return $result;
}
Upvotes: 0
Views: 805
Reputation: 2046
How's this?
((?:\b.+?\b ?){3})
Replace with:
<span>$1</span>
So in your code:
$string = 'Helping customers to do something everyday';
$pattern = '/((?:\b.+?\b ?){3})/';
$replacement = '<span>$1</span>';
echo preg_replace($pattern, $replacement, $string);
My regex tester shows this as the result:
<span>Helping customers to </span><span>do something everyday</span>
I'm not 100% au fait with PHP, so let me know how you go!
Upvotes: 0
Reputation: 2040
This is a little like @tandu's response, but I just prefer this method. It won't put a span tag at the end of the line.
function insert_tags($string) {
$exString = explode(' ', $string);
$newString = array();
for($i=0; $i < sizeof($exString); $i++) {
if($i % 3 == 0 and $i != 0) {
$newString[] = '</span><span>';
}
$newString[] = $exString[$i];
}
$newString = implode(' ', $newString);
return $newString;
}
Test returns:
Helping customers to <span></span> do something everyday
Helping customers to <span></span> do something everyday <span></span> okay there a
Helping customers to <span></span> do something everyday <span></span> okay there a <span></span> a
Helping customers to <span></span> do something everyday <span></span> okay there
Upvotes: 1
Reputation: 191729
You could do it with a regex:
`preg_replace('/\b\w+\b{3}/', '\0 </span><span>' ...`
But it may be nicer to do it with an array, assuming words are separated only by single spaces:
$words = explode(' ', $string);
$chunks = array_chunk($words, 3);
$final = '';
foreach ($chunks as $words) {
$final .= implode(' ', $words) . ' </span><span>';
}
Note that both of these can have a final </span><span>
, so if that's a problem you will have to trim it manually or just improve on what I've done.
Upvotes: 1