I'm using PHP to filter my title to remove the word "Tag:" inside and it is working fine, however when my following word starts with "T" it will instantly be removed as well.
This was how i've set my code
<?php $tag = "Tag: ";
if( str_replace( $tag, "", $title) == true ):
else:echo ltrim($title, $tag);
endif ?>
so when my title is Tag: Home it will return Home just fine,
but if my title is something like Tag: Teachers it will return me eachers instead.
How do i make it so I can still display any title starting with T without it being removed.
Try this. it will returns only Teacher
$str = "Tag: Teacher";
$str = str_replace("Tag:", "", $str);
echo $str;
Use following to remove the tag Tag:
<?php
$title = 'Tag: Teachers';
echo removeTag($title); // Teachers
function removeTag(string $str, string $tag = "Tag: "): string
{
$str = str_replace($tag, "", $str);
return $str;
}
Related
I have a link being outputted on my site, what i want to do is replace the visible text that the user sees, but the link will always remain the same.
There will be many different dynamic urls with the text being changed, so all the example regex that i have found so far only use exact tags like '/.*/'...or something similar
Edited for a better example
$link = '<a href='some-dynamic-link'>Text to replace</a>';
$pattern = '/#(<a.*?>).*?(</a>)#/';
$new_text = 'New text';
$new_link = preg_replace($pattern, $new_text, $link);
When printing the output, the following is what i am looking for, against my result.
Desired
<a href='some-dynamic-link'>New text</a>
Actual
'New text'
As you're already using the capture groups, why not actually use them.
$link = "<a href='some-dynamic-link'>Text to replace</a>";
$newText = "Replaced!";
$result = preg_replace('/(<a.*?>).*?(<\/a>)/', '$1'.$newText.'$2', $link);
If you needs to get everything in Between tags then you can use below function
<?php
function getEverything_inBetween_tags(string $htmlStr, string $tagname)
{
$pattern = "#<\s*?$tagname\b[^>]*>(.*?)</$tagname\b[^>]*>#s";
preg_match_all($pattern, $htmlStr, $matches);
return $matches[1];
}
$str = 'see here for more details about test.com';
echo getEverything_inBetween_tags($str, 'a');
//output:- see here for more details about test.com
?>
if you needs to extract HTML Tag & get Array of that tag
<?php
function extractHtmlTag_into_array(string $htmlStr, string $tagname)
{
preg_match_all("#<\s*?$tagname\b[^>]*>.*?</$tagname\b[^>]*>#s", $htmlStr , $matches);
return $matches[0];
}
$str = '<p>test</p>test.com<span>testing string</span>';
$res = extractHtmlTag_into_array($str, 'a');
print_r($res);
//output:- Array([0] => "amazon.in/xyz/abc?test=abc")
?>
Okay suppose we would like to get title,keywords and description of website so i'm going to use the following function
<?PHP
function getInfo($URL)
{
$getInfo= get_meta_tags($URL);
return $getInfo;
}
$URL = "http://www.my_site.com"; // URL
// Applying the function
$_getInfo = getInfo($URL);
// Print the results.
echo $_getInfo ["keywords"]."<br>"; // gives keywords
echo $_getInfo ["description"]."<br>"; // gives description
?>
Yet,everything if fine but suppose the results as following
Keywords
php,profitable,share
Description
Advanced profitable and featured script to share
As in this example we've some keywords found in description profitable and share
The question is how to highlight keywords that only found in description!!
I will add the following css
<style>
.highlight{background: #CEDAEB;}
.highlight_important{background: #F8DCB8;}
</style>
and will add this function to alter between two different colors just like in css code
<?PHP
function hightlight($str, $keywords = '')
{
$keywords = preg_replace('/\s\s+/', ' ', strip_tags(trim($keywords))); // filter
$style = 'highlight';
$style_i = 'highlight_important';
$var = '';
foreach (explode(' ', $keywords) as $keyword) {
$replacement = "<span class='".$style."'>".$keyword."</span>";
$var .= $replacement." ";
$str = str_ireplace($keyword, $replacement, $str);
}
$str = str_ireplace(rtrim($var), "<span class='".$style_i."'>".$keywords."</span>", $str);
return $str;
}
?>
Now applying both (Not working)
$string = hightlight($_getInfo["description"], $_getInfo ["keywords"]);
echo $string;
Why not working cause it define $_getInfo ["keywords"] as one word php,profitable,share
which indeed not found in description in that shape.
so how can i apply it by using explode or foreach (i guess) so the out put be like this :
I wonder if there was another way to do it if mine looks not good way. ~ Thanks
Since your keywords are in list format you need to:
foreach(explode(',', $keywords) as $keyword)
I am working on a project and I am facing a problem that "span>" also prints in the start of text I tried to remove all the tags every thing gone finely except the one i mentioned above,
here is my php code
<p>
<?php
$desc = $top_news['headline_des'];
$aa = preg_replace( '/style=(["\'])[^\1]*?\1/i', '', $desc, 2 );
if(strlen($top_news['headline_des'])>100)
{
$description = substr($aa, 1 ,850)."...";
}else{
$description = $aa;
}
echo strip_tags($description);
?>
</p>
here is the output
span >IPOR have the International Republican Institute (IRI) and the United States Agency for International....
The problem is the substr($aa, 1 ,850) call. substr starts with position 0, not 1, so what happens is this:
Input: <span>Foobar</span>
substr($input, 1, 850)
Output: span>Foobar</span>
substr cuts off happily the first char. Hence, strip_tags doesn't recognize span> as a whole tag and simply leaves it alone.
Fix: Use substr($aa, 0, 850).
$intro = ereg_replace("[</*>]", "", $intro);
$text = preg_replace("/<.+?>/", "", $text);
something like this should remove any tag in the $text variable.
If it doesn't work, you should check if the initial text you want to remove the tags from is correctly formed. For example a span > won't be removed since it isn't a tag, but a <span > would be removed without problem.
you could use strip_tags only for removing tags
With preg_replace
$desc = $top_news['headline_des'];
$search = array(
'#<style[^>]*?>.*?</style>#siU',
'#<[\/\!]*?[^<>]*?>#si'
);
echo $pregReplacedContent = preg_replace($search, "", $aa);
I am working on my php website (Not a Wordpress site) on the main index I display the two newest post. The thing is on the description it shows the entire article I find myself needing to display post excerpts maybe 35 word limit.
<?=$line["m_description"]?>
<?
$qresult3 = mysql_query("SELECT * FROM t_users WHERE u_id=".$line["m_userid"]." LIMIT 1");
if (mysql_num_rows($qresult3)<1) { ?>
<?php
// just the excerpt
function first_n_words($text, $number_of_words) {
// Where excerpts are concerned, HTML tends to behave
// like the proverbial ogre in the china shop, so best to strip that
$text = strip_tags($text);
// \w[\w'-]* allows for any word character (a-zA-Z0-9_) and also contractions
// and hyphenated words like 'range-finder' or "it's"
// the /s flags means that . matches \n, so this can match multiple lines
$text = preg_replace("/^\W*((\w[\w'-]*\b\W*){1,$number_of_words}).*/ms", '\\1', $text);
// strip out newline characters from our excerpt
return str_replace("\n", "", $text);
}
// excerpt plus link if shortened
function truncate_to_n_words($text, $number_of_words, $url, $readmore = 'read more') {
$text = strip_tags($text);
$excerpt = first_n_words($text, $number_of_words);
// we can't just look at the length or try == because we strip carriage returns
if( str_word_count($text) !== str_word_count($excerpt) ) {
$excerpt .= '... '.$readmore.'';
}
return $excerpt;
}
$src = <<<EOF
<b>My cool story</b>
<p>Here it is. It's really cool. I like it. I like lots of stuff.</p>
<p>I also like to read and write and carry on forever</p>
EOF;
echo first_n_words($src, 10);
echo "\n\n-----------------------------\n\n";
echo truncate_to_n_words($src, 10, 'http://www.google.com');
EDIT: Added functional example and accounted for punctuation and numbers in text
I have a function though other people may say it's not good because I'm still good at PHP too (tips welcome people) but this will give you what you are looking for, it may need better coding if anyone has suggestions.
function Short($text, $length, $url, $more){
$short = mb_substr($text, 0, $length);
if($short != $text) {
$lastspace = strrpos($short, ' ');
$short = substr($short , 0, $lastspace);
if(!$more){
$more = "Read Full Post";
} // end if more is blank
$short .= "...[<a href='$url'>$more</a>]";
} // end if content != short
$short = str_replace("’","'", $short);
$short = stripslashes($short);
$short = nl2br($short);
} // end short function
To Use:
say your article content is the variable $content
function($content, "35", "http://domain.com/article_post", "Read Full Story");
echo $short;
Similarly, you can adjust the function to remove $url and $more from it and just have the excerpt with ... at the end.
How can I replace a string from a particular string? Please see my example below.
$string_value="<b>Man one</b> <img src=\"http://www.abc.com/image1.jpg\">and <b>Man two</b> <img src=\"http://www.abc.com/img2.png\">";
Now my expected out put is = <b>Man one</b> and <b>man two</b>. only the image tag should be deleted.
So I have to cut the full string from "<img" to ">" from string $string_value.
So how can I cut the full string between "<img" to ">" using preg_replace or anything else.
The replacing parameter should be blank space.
Looks like you want to strip the tags. You can do it easily by calling the function strip_tags which gets HTML and PHP tags stripped from a given string.
$string_value = strip_tags($string_value);
EDIT:
Since you want to strip only the <img tag, you can make use of this function:
function strip_only($str, $tags) {
if(!is_array($tags)) {
$tags = (strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags));
if(end($tags) == '') array_pop($tags);
}
foreach($tags as $tag) $str = preg_replace('#</?'.$tag.'[^>]*>#is', '', $str);
return $str;
}
and call it as:
$string_value = strip_only($string_value,'img');
Working link
You can use regular expressions to exclude IMG tags:
<?php
$text = "Man one <img src=\"http://www.abc.com/image1.jpg\">and Man two <img src=\"http://www.abc.com/img2.png\">";
$pattern = "/<img(.*?)>/i";
$replace = '';
print preg_replace($pattern,$replace,$text);
?>
Just use strip_tags($string_value); and you will get your desired output.