Hi,
I want to replace ticks in text with other text. This method usually works, but when adding three dots, I get php warning
ltrim(): Invalid '..'-range, no character to the right of '..' or invalid range needs to be incrementing.
I don't know where to look for error, except deleting dots.
Here is the code:
$code = "some text before block
´´´´code block1´´´´
text after block
´´´´code block2...´´´´"; // I want ticks to be replaced to this: <pre><code> code block1 </code></pre>
$pattern = "´´´´"; // we are using ticks
$countCodeBlock = substr_count($code, $pattern); // count how many times pattern is written
if ($countCodeBlock > 0 && $countCodeBlock %2 == 0) // check if is pair number of pattern
{
for ($i = 0; $i < $countCodeBlock; $i++)
{
if ($i%2 == 0) {
// first pattern - open a tag
// check if text exist before first pattern
$getIndex = strpos($code, $pattern);// this is the index of first char of pattern
// substr grabs text - input str, start location, length
$textBeforeBlock = substr($code, 0, $getIndex); // first text, before first pattern
// strlen count char in string
if (strlen($textBeforeBlock) > 0) {
// show text first
echo "<p>" . htmlentities($textBeforeBlock) . "</p>";
}
// then remove that text and first pattern block
// ltrim removes white space, or removes special charaters
// ltrim input string, optional character or numbers
echo "<pre><code>";
$code = ltrim($code, $textBeforeBlock); // first delete text
$code = ltrim($code, $pattern); // then delete thoose ticks
}
else {
// second pattern, and closing a tag
$getIndex = strpos($code, $pattern);
$textBeforeBlock = substr($code, 0, $getIndex);
if (strlen($textBeforeBlock) > 0) {
echo htmlentities($textBeforeBlock); // here is the essence of the code text
}
echo "</code></pre>";
$code = ltrim($code, $textBeforeBlock);
$code = ltrim($code, $pattern);
}
}
// this is the end of code block, and if there is some rest of text, write it
if (strlen($code) > 0) {
echo "<p>" . htmlentities($code) . "</p>";
}
else
echo "<p></p>"; // this is intentional
}
else {
// there are no ticks in the code variable
echo "<p>" . "There is no code block:</p><br /><pre>" . htmlentities($code) . "</pre><p></p>";
}
echo $code;
You can copy code into php sandbox and give a try.