Giulio Muscarello
Giulio Muscarello

Reputation: 1342

Inserting a string into another one, every N characters

Say we have the string $string="lolololol|lolololol|lolololol|lolololol". As I need to display it in the browser, I want to add a <wbr> tag (see) every N (say, 50) characters, but I'm not sure of how to do it in PHP. I saw some solutions in other languages using regex, but I don't actually know how to use it, so I'd prefer other solutions.

Upvotes: 0

Views: 248

Answers (3)

bmalets
bmalets

Reputation: 3297

Ruby answer:


def put_wbr str, sub_str, num
  new_str = ""
  str.each_char{ |s| new_str.length % num == 0 ? new_str += sub_str : new_str += s }
  new_str[4..-1]
end

Upvotes: 0

aleation
aleation

Reputation: 4844

$string="lolololol|lolololol|lolololol|lolololol";
echo chunk_split($string, 7,"TRO");

Upvotes: 0

Green Black
Green Black

Reputation: 5084

You can use wordwrap for that

<?php
$string="lolololol|lolololol|lolololol|lolololol";
echo wordwrap( $string, 50, "<wbr>", true);

DEMO

Upvotes: 4

Related Questions