preg_replace to remove some unwanted divs - php

In the following code, I need to remove <div class="grid_8"></div>.
They will always be at the start and finish of my string, for example:
<div class="grid_8"><img src="http://rps.sanscode.com/site/assets/media/images/rps_mini_logo.png" border="0" alt="Rapid Print Solutions" style="margin-bottom: 30px;" />
<h1></h1>
</div>
What is a suitable regex for preg_replace to remove it? 8 can be any number between 1 and 16.
Thanks
Jason
#Amjad...
Here is my code
public function fix_grid(){
$result = db::query("select * from sc_content_components where component_value_1 like '%grid_%'")->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $item){
$json = json_decode($item['component_value_1']);
if(is_null($json)) continue;
$x = reset($json);
echo htmlspecialchars($x);
echo "<p>=======================<b>Changes to: </b></p>";
$patterns = array('/^<(div)((?:\s+\w+(?:\s*=\s*(?:(?:"[^"]*")|(?:\'[^\']*\')|[^>\s]+))?)*)\s*(\/?)>/'
, '/<\/(\div+)[^>]*>$/');
$x = preg_replace($patterns, array('',''), trim($x));
echo htmlspecialchars($x);
echo "<hr>";
$json[0]=$x;
// $ne['component_value_1'] = json_encode($json);
// db::where('component_id', $item['component_id']);
// db::update('sc_content_component', $ne);
}
}
I'm using the regex below (#Amjad Masad) and it doesn't remove the last div.
As you can see I am using trim and it doesn't seem to work

For the stated problem, this is the solution:
Edit: expanded regex =
/^\s*<div\s (?:".*?"|\'.*?\'|[^>]*?)*
(?<=\s)class\s*=\s*(["\'])\s*grid_(?:1[0-6]|[1-9])\s*\1
(?:".*?"|\'.*?\'|[^>]*?)*
>
(.*)
<\/div\s*>
\s*$/xs
replacement = "$2"

For the open
$patterns = array('/^<(div)((?:\s+\w+(?:\s*=\s*(?:(?:"[^"]*")|(?:\'[^\']*\')|[^>\s]+))?)*)\s*(\/?)>/'
, '/<\/div[^>]*>$/');
preg_replace($patterns, array('','');, trim($htmlString));

Somewhat simpler.
If the 1 to 16 is significant and part of a greater range...
$match = preg_replace("/^<([^>]*)grid_(1[0-6]|[1-9])([^>\d]*)>(.+)<([^>]*)>$/s","$4",trim($str),-1,$hmany);
if($hmany){
echo "$match <br>";
}else{ echo "No match found! <br>"; }
If the 1 to 16 is the only possible range and therefore irrelevant...
$match = preg_replace("/^<([^>]*)>(.+)<([^>]*)>$/s","$2",trim($str),-1,$hmany);
if($hmany){
echo "$match <br>";
}else{ echo "No match found! <br>"; }
Regards.

Related

Count Number Of Words In a Textarea

I have a text area that gets input from a PHP script, and I would like to count the number of words or line breaks in the textarea and echo it below the text area.
This is what the code looks like for the textarea.
<textarea name="domains" cols="120" rows="5" style="max-width:100%;">
<?php $output_array = explode(" ",$output);
$count = count($output_array);
for ($i=0;$i<$count;$i++){
echo $output_array[$i]."\n";
}
?>
</textarea><br />
<br>
<?php
preg_match_all("/(\n)/", $_POST['domains'], $matches);
$total_lines = count($matches[0]) + 1;
echo $total_lines;
?>
<br />
I tried using preg_match_all but the output I get is only "1", regardless of how many line breaks are inside the text area.
$str = 'as aa frd sad as
kjhsdf sdkjh
sd sdkjhsdf
sjkldhfh sdfjh sd';
preg_match_all("/\w+/", $str, $matches);
echo 'Words = ' . count($matches[0]);
echo PHP_EOL;
preg_match_all("/\n/", $str, $matches);
echo 'newlines = ' . count($matches[0]);
echo PHP_EOL;
echo 'So number of line is = ' . count($matches[0])+1;
RESULT
Words = 12
newlines = 3
So number of line is = 4
You can do the following:
$arr = array_filter(explode(" ", $input) function($item) {
return !!$item;
});
$count = count($arr) + count(explode("\n", implode(",", $arr)));
This splits the string by space, filters out empty items to avoid issues due to multiple spaces found between words, then glues the array back into a string, splits it by newline and adds the two counts together.

Remove one extra line break in a text in php

My question is exactly opposite to this one i added last night .
Need to remove the last br tag.
Input:
Test1 is here<br><br>Now comes Test2<br><br>Then test 3<br><br><br>Thats it.
Output
Test1 is here<br>Now comes Test2<br>Then test 3<br><br>Thats it.
My try:
preg_replace("[((?:<br>)+)]","",$posttext)
It removes all breaks.
You can substitute
<br><br>(?!<br)
to <br>
preg_replace('/<br><br>(?!<br)/', "<br>", $posttext);
The lookahead will prevent to match any more <br>
See demo at regex101
Feast your eyes on this hahaha
If Preg replace doesn't work...
// cuts off one <br> as high as whatever $i is at
$string = "Test1 is here<br><br>Now comes Test2<br><br>Then test 3<br><br><br>Thats it.";
$i = 10;
while($i > 0)
{
$ii = 1;
$brake = "<br>";
$replace = "";
while($ii < $i)
{
$brake .= "<br>";
$replace .= "<br>";
$ii++;
}
$string = str_replace($brake,$replace,$string);
$i--;
}
echo $string; // Test1 is here<br>Now comes Test2<br>Then test 3<br><br>Thats it.
PS: If theres no preg replace for this, it is usable albeit very inefficent.

issus with emoji in array

In this code, when I use ":-)" emoji doesn't show in output.
But when use "1f60a" OR "1f60c" OR "e252" emoji are shown. What's the problem?
<?php
$emoji_url = "http://coremobile.ir/images_smileys";
$emoji_style = "";
$emoji_code = array(
":-)",
"1f60a",
"1f60c",
"e252"
);
$emoji_img = array(
'<img src="'.$emoji_url.'/1f60a.png" '.$emoji_style.'>',
'<img src="'.$emoji_url.'/1f60a.png" '.$emoji_style.'>',
'<img src="'.$emoji_url.'/1f60c.png" '.$emoji_style.'>',
'<img src="'.$emoji_url.'/e252.png" '.$emoji_style.'>'
);
$ret = 'This Test :-) 1f60a';
$ret = str_replace($emoji_code, $emoji_img, $ret);
echo $ret;
?>
This should work for you:
(Just use strtr() instead of str_replace(), so that it won't go through the string multiple times)
$ret = strtr($ret, array_combine($emoji_code, $emoji_img));
output:
This Test
The otherone didn't worked, because it replaced every match for the first replacement and then the second and so on.
0 replaced:
This Test :-) 1f60a
//^^^ match
first replaced:
This Test <img src="http://coremobile.ir/images_smileys/1f60a.png" > 1f60a
//^^^^^ match ^^^^^ match
second replaced:
This Test <img src="http://coremobile.ir/images_smileys/<img src="http://coremobile.ir/images_smileys/1f60a.png" >.png" > <img src="http://coremobile.ir/images_smileys/1f60a.png" >

How to colorize text betwen " * " tags in message?

Anybody knows how i can achieve this:
I want post message and colorize everything between " * " Tags.
Like this:
This [*]is[*] test [*]message[*] :)
To:
This [yellow]is[/yellow]> test [yellow]message[/yellow] :)
I wroted something like this to achieve my goal:
if(preg_match_all('/\*(.*?)\*/',$message,$match)) {
$beforemessage = explode("*", $message, 2);
$message = $beforemessage[0]. " <font color='yellow'>" .$match[0][0]. "</font>";
}
Howewer it returns only:
This [yellow]is[yellow]
Just use preg_replace():
$message = "This *is* test *message*";
echo preg_replace('/\*(.*?)\*/', '<font color="yellow">$1</font>', $message);
This <font color="yellow">is</font> test <font color="yellow">message</font>
preg_match_all returns an array of matches, but your code only ever replaces the FIRST match in that array. You'd have to loop over the array to handle the OTHER matches.
There are a few approaches when using regular expressions.
One is to do matching - keeping track of the position of the match and the length of the match. Then you can split up the original message into substrings and concatenate it all back together.
The other is to do search/replace using regular expressions.
Try this, or similar approach:
<?php
$text = "Hello hello *bold* foo foo *fat* foo boo *think* end.";
$tagOpen = false;
function replaceAsterisk($matches) {
global $tagOpen;
$repl = "";
if($tagOpen) {
$repl = "</b>";
} else {
$repl = "<b>";
}
$tagOpen = !$tagOpen;
return $repl;
}
$result = preg_replace_callback( "/[*]/", "replaceAsterisk", $text);
echo $result;

Replacing symbol strange situation

foreach($ret as $object)
{
$res = $object->...;
$img_src = $res[0]->src;
echo $img_src . '<br />';
echo str_replace("&size=2", "", $img_src) . '<br /><br />';
}
$img_src ~ 'http://site.com/img.jpg&size=2'
And I have to receive same link but without &size=2. Why doesn't work my last line in code. It shows the same url.
Are you absolutely certain there are any goofy unprintable characters in your source string? Try debugging with this:
printf("%s\n", join(':', str_split($img_src)));
And make sure you really have &size=2 in your string. If you see two consecutive colons, you've got something like a \0 or some other character mucking up the works in the middle of your string.
Seems to work on this end:
http://site.com/img.jpg&size=2
http://site.com/img.jpg
from
<?php
$img_src = 'http://site.com/img.jpg&size=2';
echo $img_src.'<br />';
echo str_replace("&size=2", "", $img_src).'<br/><br/>';
?>
use preg_replace:
$c=preg_replace("/&size=2/","",$img_src);
Example of usage
<?php
$sr="http://site.com/img.jpg&size=2";
echo preg_replace("/&size=2/","",$sr);
?>
This will output
http://site.com/img.jpg

Categories