Woocommerce remove link in description product with preg_replace - php

Following a prestashop site transfer to woocommerce, I would like to remove all the old links added in the product description tab in order to avoid 404 errors. The description.php file contains :
the_content();
I would like to remove all the links present in the_content(), but keep the text.
I've tried preg_replace like this :
$content = the_content();
echo preg_replace("/<a\s+href=['\"]([^'\"]+)['\"][^\>]*>[^<]+<\/a>/i",'$1', $content);
but it does not work.

Does this do what you want? I move the parentheses in the regex.
$string = "Remove the link (<a href='http://example.com'>Link Text 1</a>) here";
$string .= "\n";
$string .= 'Remove another (Link Text 2) link';
$pattern = "/<a\s+href=['\"][^'\"]+['\"][^\>]*>([^<]+)<\/a>/i";
$replacement = '';
echo preg_replace($pattern, '$1', $string);
Result
Remove the link (Link Text 1) here
Remove another (Link Text 2) link

Related

How to preg_match_all to get the text inside the tags "<h3>" and "<h3> <a/> </h3>"

Hello I am currently creating an automatic table of contents my wordpress web. My reference from
https://webdeasy.de/en/wordpress-table-of-contents-without-plugin/
Problem :
Everything goes well unless in the <h3> tag has an <a> tag link. It make $names result missing.
I see problems because of this regex section
preg_match_all("/<h[3,4](?:\sid=\"(.*)\")?(?:.*)?>(.*)<\/h[3,4]>/", $content, $matches);
// get text under <h3> or <h4> tag.
$names = $matches[2];
I have tried modifying the regex (I don't really understand this)
preg_match_all (/ <h [3,4] (?: \ sid = \ "(. *) \")? (?:. *)?> <a (. *)> (. *) <\ / a> <\ / h [3,4]> /", $content, $matches)
// get text under <a> tag.
$names = $matches[4];
The code above work for to find the text that is in the <h3> <a> a text </a> <h3> tag, but the h3 tag which doesn't contain the <a> tag is a problem.
My Question :
How combine code above?
My expectation is if when the first code result does not appear then it is execute the second code as a result.
Or maybe there is a better solution? Thank you.
Here's a way that will remove any tags inside of header tags
$html = <<<EOT
<h3>Here's an alternative solution</h3> to using regex. <h3>It may <a name='#thing'>not</a></h3> be the most elegant solution, but it works
EOT;
preg_match_all('#<h(.*?)>(.*?)<\/h(.*?)>#si', $html, $matches);
foreach ($matches[0] as $num=>$blah) {
$look_for = preg_quote($matches[0][$num],"/");
$tag = str_replace("<","",explode(">",$matches[0][$num])[0]);
$replace_with = "<$tag>" . strip_tags($matches[2][$num]) . "</$tag>";
$html = preg_replace("/$look_for/", $replace_with,$html,1);
}
echo "<pre>$html</pre>";
The answer #kinglish is the base of this solution, thank you very much. I slightly modify and simplify it according to my question article link. This code worked for me:
preg_match_all('#(\<h[3-4])\sid=\"(.*?)\"?\>(.*?)(<\/h[3-4]>)#si',$content, $matches);
$tags = $matches[0];
$ids = $matches[2];
$raw_names = $matches[3];
/* Clean $rawnames from other html tags */
$clean_names= array_map(function($v){
return trim(strip_tags($v));
}, $raw_names);
$names = $clean_names;

Replacing Relative Links with External Links in PHP String

I am working with an editor that works purely with internal relative links for files which is great for 99% of what I use it for.
However, I am also using it to insert links to files within an email body and relative links don't cut the mustard.
Instead of modifying the editor, I would like to search the string from the editor and replace the relative links with external links as shown below
Replace
files/something.pdf
With
https://www.someurl.com/files/something.pdf
I have come up with the following but I am wondering if there is a better / more efficient way to do it with PHP
<?php
$string = 'A link, some other text, A different link';
preg_match_all('/<a[^>]+href=([\'"])(?<href>.+?)\1[^>]*>/i', $string, $result);
if (!empty($result)) {
// Found a link.
$baseUrl = 'https://www.someurl.com';
$newUrls = array();
$newString = '';
foreach($result['href'] as $url) {
$newUrls[] = $baseUrl . '/' . $url;
}
$newString = str_replace($result['href'], $newUrls, $string);
echo $newString;
}
?>
Many thanks
Lee
You can simply use preg_replace to replace all the occurrences of files starting URLs inside double quotes:
$string = 'A link, some other text, A different link';
$string = preg_replace('/"(files.*?)"/', '"https://www.someurl.com/$1"', $string);
The result would be:
A link, some other text, A different link
You really should use DOMdocument for such job, but if you want to use a regex, this one does the job:
$string = '<a some_attribute href="files/something.pdf" class="abc">A link</a>, some other text, <a class="def" href="files/somethingelse.pdf" attr="xyz">A different link</a>';
$baseUrl = 'https://www.someurl.com';
$newString = preg_replace('/(<a[^>]+href=([\'"]))(.+?)\2/i', "$1$baseUrl/$3$2", $string);
echo $newString,"\n";
Output:
<a some_attribute href="https://www.someurl.comfiles/something.pdf" class="abc">A link</a>, some other text, <a class="def" href="https://www.someurl.com/files/somethingelse.pdf" attr="xyz">A different link</a>

PHP : add a html tag around specifc words

I have a data base with texts and in each text there are words (tags) that start with # (example of a record : "Hi I'm posting an #issue on #Stackoverflow ")
I'm trying to find a solution to add html code to transform each tag into a link when printing the text.
So the text are stored as strings in MySQL database like this :
Some text #tag1 text #tag2 ...
I want to replace all these #abcd with
#abcd
And have a final result as follow:
Some text #tag1 text #tag2 ...
I guess that i should use some regex but it is not at all my strong side.
Try the following using preg_replace(..)
$input = "Hi I'm posting an #issue on #Stackoverflow";
echo preg_replace("/#([a-zA-Z0-9]+)/", "<a href='targetpage.php?val=$1'>#$1</a>", $input);
http://php.net/manual/en/function.preg-replace.php
A simple solution could look like this:
$re = '/\S*#(\[[^\]]+\]|\S+)/m';
$str = 'Some text #tag1 text #tag2 ...';
$subst = '#$1';
$result = preg_replace($re, $subst, $str);
echo "The result of the substitution is ".$result;
Demo
If you are actually after Twitter hashtags and want to go crazy take a look here how it is done in Java.
There is also a JavaScript Twitter library that makes things very easy.
Try this the function
<?php
$demoString1 = "THIS is #test STRING WITH #abcd";
$demoString2 = "Hi I'm posting an #issue on #Stackoverflow";
function wrapWithAnchor($link,$string){
$pattern = "/#([a-zA-Z0-9]+)/";
$replace_with = '<a href="'.$link.'?val=$1">$1<a>';
return preg_replace( $pattern, $replace_with ,$string );
}
$link= 'http://www.targetpage.php';
echo wrapWithAnchor($link,$demoString1);
echo '<hr />';
echo wrapWithAnchor($link,$demoString2);
?>

Display Longtext Description Output

Hello how to display the content on the database correctly
[center][youtube]vn9mMeWcgoM[/youtube] [/center]
[center]This is a test youtube post video [/center][center][img]http://3.bp.blogspot.com/-RgszeTgP4eA/Vck93de-LZI/AAAAAAAAaOQ/F0s-XK5Zh4c/w1200-h630-p-k-no-nu/samabawan_island_leyte_philippines.jpg[/img][/center]
That is the Output it should display the image and video
This is my display code
<?php echo nl2br($item['content']); ?>
The way you can do this by using preg_replace()
And this is a simple function i have written, i hope this helps you.
$text = "[center][youtube]vn9mMeWcgoM[/youtube] [/center] [center]This is a test youtube post video [/center][center][img]http://3.bp.blogspot.com/-RgszeTgP4eA/Vck93de-LZI/AAAAAAAAaOQ/F0s-XK5Zh4c/w1200-h630-p-k-no-nu/samabawan_island_leyte_philippines.jpg[/img][/center]";
function replace($string){
$string = preg_replace("/\[center\](.*?)\[\/center]/", "<div align='center'>$1</div>", $string);
$string = preg_replace("/\[youtube\](.*?)\[\/youtube]/", "<iframe src=\"https://www.youtube.com/embed/$1\"></iframe>", $string);
$string = preg_replace("/\[img\](.*?)\[\/img]/", "<img src='$1' />", $string);
return $string;
}
echo replace($text);
For your code, call it like this, echo nl2br(replace($item['content']));
EDITED
Here is the way you can add more tags,
First read about the function preg_replace()
And read Possible modifiers in regex patterns for more informations.
Now you can add,
$string = preg_replace("/\[url\](.*?)\[\/url]/", "<a href=\"$1\" >$1</a>", $string);
After last $string variable in my simple function.
This mean replace what inside URL tags with <a href=\"$1\" >$1</a>
And $1 is the URL, in most cases $1 is the element you want.

How work with preg_replace to replace with excluded pattern

I have some text contain html tags, I would like to replace all links with other one, but I want to replace just local links, not they start with http://
example :
test link
==> test link
Video
==> Video
I try this preg_replace but not working :
$exclude = '<a href=\"http://.*?';
$pattern = '<a href=\".*?';
$content=preg_replace("~(($exclude)?($pattern))~i",'<a href="/action.php?url=$4',$content);
Thanks!
What about something like this:
$content = preg_replace('#<a href="([^:]*)">#i', '<a href="/action.php?url=$1">', $content);

Categories