I want to insert string in certain position of character using PHP, so I have string like this:
$string = "
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>10</p>
<p>11</p>
<p>12</p>
<p>13</p>
<p>14</p>
<p>15</p>
<p>16</p>
<p>17</p>
";
I want to append this bb code [next]
after every multiple of 5 </p>
tag, so it would be like this:
$string = "
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
[next] //appended bb code
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>10</p>
[next] //appended bb code
<p>11</p>
<p>12</p>
<p>13</p>
<p>14</p>
<p>15</p>
[next] //appended bb code
<p>16</p>
<p>17</p>
";
I have a case that I have a post article that needs to paginate after the fifth </p>
, tenth </p>
, fifteenth </p>
and so on. What I have tried is to find and get the number of position of each </p>
and append the [next]
bb code when at the tenth paragraph (</p>
). and that works well.
$string = "
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>10</p>
<p>11</p>
<p>12</p>
<p>13</p>
<p>14</p>
<p>15</p>
<p>16</p>
<p>17</p>
";
$paginate = '[next]';
$found = 0;
for($i = 1; $i <= 99; $i++) {
$paragraph = strpos($string, "</p>", $found);
$found = $paragraph + 1;
if ($i == 10) {
$string = substr_replace($string, $paginate, $paragraph, 0);
}
}
echo $string;
The Result (Output):
1
2
3
4
5
6
7
8
9
10[next]
11
12
13
14
15
16
17
I'm struggling when I'm tried to append that bb code every multiple of 5 </p>
tag, so any help is much appreciated.