J'essaie de diviser une chaîne de texte en deux, en faisant attention de ne pas.. :
- mots de rupture
- rupture html
Pour vous donner un peu de contexte, je veux prendre un article de blog et injecter une publicité au milieu de celui-ci.
J'ai cherché une réponse mais les seules options que j'ai trouvées sur SO suggèrent de supprimer tout le HTML - ce qui n'est pas une option...
Exemple :
$string = "<div class='some-class'>Deasdadlights blasdasde holysadsdto <span>Bri<img src='#'>cable holystone blow the man down</span></div>";
$length = strlen($string);
// At this point, something magical needs to split the string being mindful of word breaks and html
$pieces = array(
substr( $string, 0, ( $length / 2 ) ),
substr( $string, ( $length / 2 ), $length )
);
echo $pieces[0] . " **Something** " . $pieces[1];
// <div class="some-class">Deasdadlights blasdasde holysadsdto <spa **something**="" n="">Bri<img src="#">cable holystone blow the man down</spa></div>
// And there goes the <span> tag :'(
UPDATE
Merci @Naga pour la réponse ! Voici une version un peu plus développée pour ceux qui en ont besoin :
$string = '
<section class="post_content">
<p>Often half the battle is ensuring you get the time to respond to your reviews, the other half is remembering that the customer is always right and you should proceed with caution.</p>
<p>Some simple principles to keep in mind are to be <strong>positive</strong>, <strong>humble</strong>, <strong>helpful</strong>, and <strong>enthusiastic</strong>.</p>
<p>Some simple principles to keep in mind are to be <strong>positive</strong>, <strong>humble</strong>, <strong>helpful</strong>, and <strong>enthusiastic</strong>.</p>
</section>
';
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
libxml_use_internal_errors(true);
$dom->loadHTML($string); // $string is the block page full / part html
$xpath = new DOMXPath($dom);
$obj = $xpath->query('//section[@class="post_content"]'); // assume this is the container div that where you want to inject
$nodes = $obj->item(0)->childNodes;
$half = $nodes->length / 2;
$i = 0;
foreach( $nodes as $node ) {
if ( $i === $half ) {
echo "<div class='insert'></div>";
}
echo $node->ownerDocument->saveHTML($node);
$i ++;
}