I try change characters by functions
<?php
$string = "Hi everybody people [gal~images/articles~100~100~4] here other imagen [gal~images/products~100~100~3]";
$regex = "/\[(.*?)\]/";
preg_match_all($regex, $string, $matches);
for($i=0; $i<count($matches[1]);$i++)
{
$match = $matches[1][$i];
$array = explode('~', $match);
//$newValuet="gal("".$array[1]."","".$array[2]."","".$array[3]."","".$array[4]."")";
$newValue="gal(".$array[1].",".$array[2].",".$array[3].",".$array[4].")";
$string = str_replace($matches[0][$i],$newValue,$string);
}
echo $string;
?>
The problem here :
$newValue="gal(".$array[1].",".$array[2].",".$array[3].",".$array[4].")";
$string = str_replace($matches[0][$i],$newValue,$string);
Function no give the right results i try differents methods but continue the problems , please i see all functions but no get this works if you can answer please put me some modification of this code for i can understand , thank´s a lot for all help
MORE INFORMATION
The script generate new values this values must send thhe function of gall for insert and show replace tags and put all well , show text and tags replace
$newValue="gal(".$array[1].",".$array[2].",".$array[3].",".$array[4].")";
$string = str_replace($matches[0][$i],$newValue,$string);
Here the function show the gal , the function execute when must execute into str_replace for put the text , before replace the tags and continue , only this fail
P.D : I pay respect some people , i go here for send my questions howewer in many cases writte bad but english no native for me , and sure for all people here in many cases luke the people respect if no speak well , all people here need learn or need help and howewer tomorrow i can help other people or this people me , nothing more pay , thank´s
Regards
Function of gallery
<?php
function gal($dire,$w_size,$h_size,$cols)
{
$n_images=0;
$dir=opendir("$dire");
while($file=readdir($dir))
{
if ($file!="." && $file!=".." && $file!="Thumbs.db" && $file!="index.html" && $file!=".htaccess" && $file!="config.dat")
{
$n_images++;
$imagenes[]=$file;
}
}
closedir($dir);
$num_img="".$n_images."";
$num_img_cols="".$cols."";
$num_filas="".ceil($num_img/$num_img_cols)."";
echo '<table width="10%" border="0" cellpadding="3" cellspacing="2" align="center">
<tr>
<td colspan="'.$num_img_cols.'"> </td>
</tr><tr>';
$x=1;
for ($j=0;$j<$n_images;$j++)
{
print "<td align='center'>";
//echo '<img src="'.$dire.'/'.$imagenes[$j].'" width="'.$w_size.'" height="'.$h_size.'">';
print "<a href='".$dire."/".$imagenes[$j]."' class='highslide' onclick=\"return hs.expand(this,{slideshowGroup:'group1',align:'center'})\">";
print '<img src="indexer_resizer.php?ruta_f='.$dire.'/&image='.$imagenes[$j].'&new_width='.$w_size.'&new_height='.$h_size.'" border="0" alt="Pulse para Ampliar" title="Pulse para Ampliar">
</a>';
if ($x%$num_img_cols==0)
{
print "</tr>";
}
$x++;
}
echo "</table>";
}
?>
**Function for replace tags**
<?php
$string = "Hola todos os presento una nueva galeria [galt~imagenes/articulos~100~100~4] Aqui otra más [gal~imagenes/productos~100~100~3]";
$regex = "/\[(.*?)\]/";
preg_match_all($regex, $string, $matches);
for($i=0; $i<count($matches[1]);$i++)
{
$match = $matches[1][$i];
$array = explode('~', $match);
//$newValuet="gal("".$array[1]."","".$array[2]."","".$array[3]."","".$array[4]."")";
$newValue="gal(".$array[1].",".$array[2].",".$array[3].",".$array[4].")";
$string = str_replace($matches[0][$i],$newValue,$string);
}
echo $string;
?>
This is all function and you can see here , the script use 2 things the function for see gallery and the script for replace and show gallery , but no works fine
The script generate new values this values must send thhe function of gall for insert and show replace tags and put all well , show text and tags replace
$newValue="gal(".$array[1].",".$array[2].",".$array[3].",".$array[4].")";
$string = str_replace($matches[0][$i],$newValue,$string);
Here the function show the gal , the function execute when must execute into str_replace for put the text , before replace the tags and continue , only this fail
P.D : I pay respect some people , i go here for send my questions howewer in many cases writte bad but english no native for me , and sure for all people here in many cases luke the people respect if no speak well , all people here need learn or need help and howewer tomorrow i can help other people or this people me , nothing more pay , thank´s
Regards
To capture those portions of the string try:
$string = "Hi everybody people [gal~images/articles~100~100~4] here other imagen [gal~images/products~100~100~3]";
preg_match_all('/\[(.+)\]/ismU, $string, $matches);
or
preg_match_all('/\[(\w+)\~([a-z0-9\/]+)\~(\d+)\~(\d+)\~(\d+)\]/ismU, $string, $matches);
The last one results a bit more complicated structure of $matches but prooves that you'll catch exactly the data you need.
Related
I have a simple message board, let's say: mywebsite.com, that allows users to post their messages. Currently the board makes all links clickable, ie. when someone posts something that starts with:
http://, https://, www., http://www., https://www.
then the script automatically makes them as links (ie. adds the A href.. tag).
THE PROBLEM - there is too much spam. So my idea is to automatically remove the above http|s/www so that these don't become 'clickable links.' HOWEVER, I want to allow posters to link to pages within my site, ie. not to remove http|s/www when the message contains link/s to mywebsite.com.
My idea was to create two arrays:
$removeParts = array('http://', 'https://', 'www.', 'http://www.', 'https://www.');
$keepParts = array('http://mywebsite.com', 'http://www.mywebsite.com', 'www.mywebsite.com', 'http://mywebsite.com', 'https://www.mywebsite.com', 'https://mywebsite.com');
but I don't know how to use them correctly (probably str_replace could work somehow).
Below is an example of $message which is before posting and after posting:
$message BEFORE:
Hello world, thanks to http://mywebsite/about I learned a lot. I found
you on http://www.bing.com, https://google.com/search and on some www.spamwebsite.com/refid=spammer2.
$message AFTER:
Hello world, thanks to http://mywebsite.com/about I learned a lot. I
found you on bing.com, google.com/search and on some spamwebsite.com/refid=spammer2.
Please note the user enters clear text into the post form, so script should only work with this clear text (not a href etc.).
$url = "http://mywebsite/about";
$parse = parse_url($url);
if($parse["host"] == "mywebsite")
echo "My site, let's mark it as link";
More info:
http://php.net/manual/en/function.parse-url.php
killSpam() function features:
works with single and double-quotes.
Invalid html
ftp://
http://
https://
file://
mailto:
function killSpam($html, $whitelist){
//process html links
preg_match_all('%(<(?:\s+)?a.*?href=["|\'](.*?)["|\'].*?>(.*?)<(?:\s+)?/(?:\s+)?a(?:\s+)?>)%sm', $html, $match, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($match[1]); $i++) {
if(!preg_match("/$whitelist/", $match[1][$i])){
$spamsite = $match[3][$i];
$html = preg_replace("%" . preg_quote($match[1][$i]) . "%", " (SPAM) ", $html);
}
}
//process cleartext links
preg_match_all('/(\b(?:(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[A-Z0-9+&##\/%?=~_|$!:,.;-]*[A-Z0-9+&##\/%=~_|$-]|((?:mailto:)?[A-Z0-9._%+-]+#[A-Z0-9._%-]+\.[A-Z]{2,6})\b)|"(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[^"\r\n]+"|\'(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[^\'\r\n]+\')/i', $html, $match2, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($match2[1]); $i++) {
if(!preg_match("/$whitelist/", $match2[1][$i])){
$spamsite = $match2[1][$i];
$html = preg_replace("%" . preg_quote($spamsite) . "%", " (SPAM) ", $html);
}
}
return $html;
}
Usage:
$html = <<< LOB
<p>Hello world, thanks to http://mywebsite/about I learned a lot. I found
you on http://www.bing.com, https://google.com/search and on some <a href="http://www.spamwebsite.com" rel="nofollow">www.spamwebsite.com/refid=spammer2< /a >. www.spamme.com, http://morespam.com/?aff=122, http://crazyspammer.com/?money=22 and spam#email.com, file://spamfile.com/file.txt ftp://spamftp.com/file.exe </p>
LOB;
$whitelist = "(google\.com|yahoo\.com|bing\.com|nicesite\.com|mywebsite\.com)";
$noSpam = killSpam($html, $whitelist);
echo $noSpam;
Spam Example:
I CANNOT POST THE SPAM HTML HERE, I GUESS SO HAS IS OWN killSpam()...- view it at http://pastebin.com/HXCkFeGn
Hello world, thanks to http://mywebsite/about I learned a lot. I found
you on http://www.bing.com, https://google.com/search and on some www.spamwebsite.com/refid=spammer2.
www.spamme.com, http://morespam.com/?aff=122,
http://crazyspammer.com/?money=22 and spam#email.com,
file://spamfile.com/file.txt ftp://spamftp.com/file.exe
Output:
Hello world, thanks to (SPAM) I learned a lot. I found you on http://www.bing.com, https://google.com/search and on some (SPAM) .
(SPAM) , (SPAM) , (SPAM) and (SPAM) , (SPAM) (SPAM)
Demo:
http://ideone.com/9IxFrB
If u want to preserve text of links, but make them "not clickable", u may try this code:
<?php
$text = <<<__text
Hello world, thanks to http://mywebsite/about I learned a lot.
I found you on http://www.bing.com, https://google.com/search and on some www.spamwebsite.com/refid=spammer2.
www.spamme.com, http://morespam.com/?aff=122, http://crazyspammer.com/?money=22 and spam#email.com, file://spamfile.com/file.txt ftp://spamftp.com/file.exe
__text;
$allowed_domains = ['mywebsite.com'];
$pattern = "/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+#)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+#)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%#\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/";
preg_match_all($pattern, $text, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
list(, $url, $scheme_and_domain, $scheme, $path) = $m;
$domain = preg_replace(['/^' . preg_quote($scheme, '/') . '/i', "/^www./i"], '', $scheme_and_domain);
if (in_array($domain, $allowed_domains)) continue;
$url_prepared = rtrim("$domain$path", '/');
$text = str_replace($url, $url_prepared, $text);
}
echo $text;
Codepad
For anyone looking for an answer - I posted a related (more specific) question which solved the problem: PHP - remove words (http|https|www|.com|.net) from string that do not start with specific words
[caption id="attachment_1342" align="alignleft" width="300" caption="Cheers... "Forward" diversifying innovation to secure first place. "][/caption] A group of 35 students from...
I'm reading this data from api. I want the text just start with A group of 35 students from.... Help me to replace the caption tag with null. This is what I tried:
echo "<table>";
echo "<td>".$obj[0]['title']."</td>";
echo "<td>".$obj[0]['content']."</td>";
echo "</table>";
$html = $obj[0]['content'];
preg_match_all('/<caption>(.*?)<\/caption>/s', $html, $matches);
preg_replace('',$matches, $obj[0]['content']);
Any help.
$pattern = "/\[caption (.*?)\](.*?)\[\/caption\]/i";
$removed = preg_replace($pattern, "", $html);
echo preg_replace("#\[caption.*\[/caption\]#u", "", $str);
In the snippet mentioned in the question, regex search pattern is incorrect. there is no <caption> in the input. its <caption id....
Second using preg_replace doesn't serve any purpose here. preg_replace expects three arguments. first should be a regex pattern for search. second the string to replace with. and third is input string.
Following snippet using preg_match will work.
<?php
//The input string from API
$inputString = '<caption id="attachment_1342" align="alignleft" width="300" caption="Cheers... "Forward" diversifying innovation to secure first place. "></caption> A group of 35 students from';
//Search Regex
$pattern = '/<caption(.*?)<\/caption>(.*?)$/';
//preg_match searches inputString for a match to the regular expression given in pattern
//The matches are placed in the third argument.
preg_match($pattern, $inputString, $matches);
//First match is the whole string. second if the part before caption. third is part after caption.
echo $matches[2];
// var_dump($matches);
?>
if you still want to use preg_match_all for some reason. following snippet is modification of the one mentioned in question -
<?php
//Sample Object for test
$obj = array(
array(
'title' => 'test',
'content' => '<caption id="attachment_1342" align="alignleft" width="300" caption="Cheers... "Forward" diversifying innovation to secure first place. "></caption> A group of 35 students from'
)
);
echo "<table border='1'>";
echo "<td>".$obj[0]['title']."</td>";
echo "<td>".$obj[0]['content']."</td>";
echo "</table>";
$html = $obj[0]['content'];
//preg_match_all will put the caption tag in first match
preg_match_all('/<caption(.*?)<\/caption>/s', $html, $matches2);
//var_dump($matches2);
//use replace to remove the chunk from content
$obj[0]['content'] = str_replace($matches2[0], '', $obj[0]['content']);
//var_dump($obj);
?>
Thank you guys. I use explode function to do this.
$html = $obj[0]['content'];
$code = (explode("[/caption]", $html));
if($code[1]==''){
echo $code[1];
}
OK, so I'm not sure why but when i try to use preg_replace() on array items returned with mysql_fetch_array() I get no results but if I take those same results, make an array out of them it works fine.
Example
$pattern = '/^.*\b([0-9]{6}\s\D\d|[0-9]{6}\s\D[0-9]{2}|[0-9]{7}\s\D[0-9]{2})\b.*$/';
$replace = '$1';
while($row = mysql_fetch_assoc($result))
{
$data[] = $row['description'];
}
foreach($data as $datas)
{
echo preg_replace($pattern, $replace, $datas) . '<br>';
echo '<br>';
}
all this does is return no matches, but if I copy those results and put them in an array it works fine and I know it's not the regex because I tested that before I got this far. Here is an example of the items working when I define them in a seperate array:
$subject = array(
"Suzuki DR100 ignition pickup. Wires to the coils have been repaired and one needs to be repaired again. 082862 S15 <img src = \">http://www.roofis27.com/motorcycle/12_08_28/061.JPG\">",
"1997 Suzuki VZ800 Marauder, Kick stand and spring. Chrome on end is starting to chip. 0121103 S19 <img src = \">http://www.roofis27.com/motorcycle/13_01_21/103.JPG\">",
"Honda 1982 VF750C Magna right-side radiator trim panel. Good, damage-free condition. Needs cut and polished. Cheap, fast shipping! 011425 H6 <img src=\">http://www.roofis27.com/motorcycle/10_01_14/030.JPG\"> n=\">",
);
foreach ($subject as $subjects)
{
echo preg_replace($pattern, $replace, $subjects) . '<br>';
}
Returns:
082862 S15
0121103 S19
011425 H6
So my question is how can i use preg_replace() on an array returned from mysql_fetch_array()?
or how else can you search and replace these codes within MySQL.
Just so I'm sure to make myself clear this time:
I have a MySQL database that has these location codes within the product_description, they are all right before the <img> tag within a long product description. I need them placed into the the model column of the database, which is in another table. I have no problem using SQL to do this, but cannot get these location codes removed from the description & by themselves. MySQL does not allow regex to be used this way that i am aware of so I'm trying to do it with php instead.
Any help please! I'm really stuck.....
After talking to some people, apparently there are characters in the return from mysql_fetch_array() that are invisible and that's why the regexp does not work. I got way better results using preg_match() as follows:
foreach($data as $datas)
{
$pattern = '([0-9]{6}\s\D[0-9]{2}|[0-9]{6}\s\D\d|[0-9]{7}\s\D[0-9]{2})';
preg_match($pattern, $datas, $matches, PREG_OFFSET_CAPTURE);
foreach($matches as $match){
echo $match[0] . '<br>';
}
}
I'm struggling on replacing text in each link.
$reg_ex = "/(http|https)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$text = '<br /><p>this is a content with a link we are supposed to click</p><p>another - this is a content with a link we are supposed to click</p><p>another - this is a content with a link we are supposed to click</p>';
if(preg_match_all($reg_ex, $text, $urls))
{
foreach($urls[0] as $url)
{
echo $replace = str_replace($url,'http://www.sometext'.$url, $text);
}
}
From the code above, I'm getting 3x the same text, and the links are changed one by one: everytime is replaced only one link - because I use foreach, I know.
But I don't know how to replace them all at once.
Your help would be great!
You don't use regexes on html. use DOM instead. That being said, your bug is here:
$replace = str_replace(...., $text);
^^^^^^^^--- ^^^^^---
you never update $text, so you continually trash the replacement on every iteration of the loop. You probably want
$text = str_replace(...., $text);
instead, so the changes "propagate"
If you want the final variable to contain all replacements change it so something like this...
You basically are not passing the replaced string back into the "subject". I assume that is what you are expecting since it's a bit difficult to understand the question.
$reg_ex = "/(http|https)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$text = '<br /><p>this is a content with a link we are supposed to click</p><p>another - this is a content with a link we are supposed to click</p><p>another - this is a content with a link we are supposed to click</p>';
if(preg_match_all($reg_ex, $text, $urls))
{
$replace = $text;
foreach($urls[0] as $url) {
$replace = str_replace($url,'http://www.sometext'.$url, $replace);
}
echo $replace;
}
I have a CMS where i can insert texts with direct links to my favorite sites, to be viewed in the FrontPage, but i just want to show the name of them (bold or colored) and not the URL. How can i do it!?
I´m using a DB with some other info and works great, but I'm not achieving this part. any solution!?
Thanks in advance..
Try this.
<?php
function getTextBetweenTags($string, $tagname) {
$pattern = "/<$tagname ?.*>(.*)<\/$tagname>/";
preg_match($pattern, $string, $matches);
return $matches[0];
}
$str = '<span style="text-decoration: underline;">Some</span>';
$txt = getTextBetweenTags($str, "a");
echo $txt;
?>