multi step string split using php - php

I have a Wordpress site that I am building for a client and one custom post type field will allow users to enter a link and then the text for the link in a format as pictured below and called resources.
That info them needs to be output in an anchor tag as a <li>. I am newish to php and this is what I have so far for code
<ul>
<?php
$rawcontent = get_field("resources");
$rawcontent = preg_replace("!</?p[^>]*>!", "", $rawcontent);
$all_links = preg_split("/(\n)/", $rawcontent);
$firstpart = array_pop(explode(',', $rawcontent));
foreach($all_links as $link) {
if(!trim($link)) continue;
echo "<li><a href='$link'>$firstpart</a></li>";
}
?>
</ul>
when I print $rawcontent (resources) before any of my code executes is apperas as:
www.mylink1.com,link copy 1
www.mylink2.com, link copy 2
www.mylink3.com,link copy 3
with the code I have implemented now it comes out as
How can I get this to return just the link for the href and the just the link copy part for the anchor text for each anchor tag?

I think this will do it.
I first explode on new line just like you do, then I foreach the lines.
When I foreach the lines I explode the line on comma.
Now I have an array with link as first item, and text as the second item.
$str = "www.mylink1.com,link copy 1
www.mylink2.com, link copy 2
www.mylink3.com,link copy 3";
$lines = explode(PHP_EOL, $str);
Foreach($lines as $line){
$linktext = explode(",", $line);
Echo "<li><a href='$linktext[0]'>$linktext[1]</a></li>";
}
https://3v4l.org/9DEoo
I see that your link2 has a space in the text.
You can remove that with trim when you echo.
Echo "<li><a href='" . trim($linktext[0]) . "'>" . trim($linktext[1]) . "</a></li>\n";
I added trim on both link and text, it can be good to have. Just in case...
https://3v4l.org/6RkW3

Related

Trying to Replace h2's with Anchor Links within the_content() dynamically

I am trying to create a side anchor navigation that will build out the side nav for every h2 tag header. I have the side nav portion working just the way I want it to. It pulls the h2 out of the wordpress the_content and creates an anchor link and replaces the value of the h2 with a string such as (#-this-is-an-anchor) if the first h2 in the_content is This Is An Anchor.
The part Im having a problem with is wrapping the_content h2's with the anchor id to connect to the side nav values. The below code is to display the body content, which is what Im having issues with.
<?php
$content = get_the_content();
preg_replace_callback( '#<h2.*?>(.*?)<\/h2>#',function($matches) {
global $h;
$h = array();
$h[] = $matches[1];
return'';
}, $content);
$anchor_div = '';
foreach($h as $h_tag) {
$anchor_div = str_replace(' ','-',strtolower($h_tag));
}
echo preg_replace('#<h2.*?>(.*?)<\/h2>#','<div id="'. $anchor_div .'"><h2>'. $h_tag.'</h2></div>', $content);
?>
Now this is working, however only the last h2 value is being displayed as the h2 replacement and the anchor link. You can see in the image what Im trying to do. This works if I wrap the preg_replace within the foreach statement, but duplicates everything. So having it outside is showing the right amount of content, but like I said, the last anchor value is only showing in the body.
Thanks for your help.
$anchors = [];
$new = preg_replace_callback('#(<h2.*?)>(.*?)<\/h2>#',function($matches) use(&$anchors) {
$anchor = str_replace(' ', '-', strtolower($matches[2]));
$anchors[] = [$matches[2], $anchor];
return $matches[1] . ' id="' . $anchor . '">' . $matches[2] . '</h2>';
}, $text);
This adds the id attribute to the h2 elements, and in $anchors you find the original h2 text contents and the used ids, so that you can create your navigation based on that.

How to delete a specific tag using regex

I'm trying to delete a ul tag and nested tags inside that ul.
<ul class="related">
<li>Related article</li>
<li>Related article 2</li>
</ul>
I just deleted the nested li inside the ul using this (I'm using php for this thing, so I pulled content from a db as $content)
$content = $rq['content']; //here is the <ul class="related">... code
$content1 = preg_replace('~<ul[^>]*>\K(?:(?!<ul).)*(?=</ul>)~Uis', '', $content); //it works here
So far I get the next string in $content1
<ul class="related"></ul>
So how do I delete this piece of remaining code using regex? I tried the similar pattern but did not get the results I am wanting.
$finalcontent = preg_replace('~<ul[^>]*>\K.*(?=</ul>)~Uis', '', $content1);
The following may suit your purpose:
$content1 = '<p>Foo</p><ul class="related"></ul><p>Bar</p>';
$finalcontent = preg_replace('~<ul[^>]*>.*</ul>~Uis', '', $content1);
echo $finalcontent;
The preg_replace call should remove all occurrences of <ul...>...</ul> from $content1. For the given example content, it returns:
<p>Foo</p><p>Bar</p>
If you want the replacement to be more specific, e.g., in order to only remove occurrences of <ul class="related">...</ul> but not other types of <ul>...</ul>, you can make the regex more specific. For example:
$content1 = '<p>Foo</p><ul class="related"></ul><p>Bar</p><ul><li>Do not delete this one</li></ul>';
$finalcontent = preg_replace('~<ul class="related">.*</ul>~Uis', '', $content1);
echo $finalcontent;
For the given example, this would return:
<p>Foo</p><p>Bar</p><ul><li>Do not delete this one</li></ul>

Extract image data when pulling in RSS feeds using PHP

The script I am using to pull in the feed titles is:
<?php
function getFeed($feed_url) {
$content = file_get_contents($feed_url);
$x = new SimpleXmlElement($content);
echo "<ul>";
foreach($x->channel->item as $entry) {
echo "<li><a href='$entry->link' title='$entry->title'>" . $entry->title . "</a> </li>";
$i++;
if($i==5) break;
}
echo "</ul>";
}
?>
I would like to pull in the images for each title/article and place them next to the title.
The float part is easy. I'm having trouble getting the actual image in. I've tried that mark like this: <img src="$entry->image" />, but it didn't work.
How would I go about this please?
As the answer to random's suggestion:
I'm using $item['description'] to represent the description string.
Then match for img tag
Output image tag
Then remove the image tag from the original $content and output that, you're left with just the description text
<?php
$content = $item['description'];
preg_match('/(<img[^>]+>)/i', $content, $matches);
echo $matches[0];
echo str_replace($matches[0],"",$content);
?>
When displaying the feed contents, variables such as $entry->link and $entry->title work because they are valid, present and required elements in a standard RSS feed item.
To call $entry->image would require the source RSS to use and populate that optional element.
Some feeds may include that data, but most will not.
Alternatively, you can write your own function or method to scan the contents of the description element and find any suitable image to include as you need.

Divide text string into sections (separate divs) of 500 characters (or any other # of characters) using PHP?

What is the best method for taking a text string (from a mysql database, like a wordpress post or page) and dividing the text into sections of 500 characters (or any other number of characters), and then outputting each 500-character section wrapped in its own div container?
Being new to PHP, I'm not sure how to go about segmenting the content based on character count. We could get the character count using:
<?php
$content = get_the_content(); //wordpress function for post content as string.
echo strlen($content);
?>
But that is as far as my knowledge goes. Can anyone help me out with this challenge?
Let's say I was requesting a page of content from the wordpress database, and it was 5,000 characters long. The goal would be to output 10 divs or spans that each contained 500 characters.
THANK YOU in advance for any assistance.
PHP offers a function for that, it is called 'str_split()'. You can use it like this:
<?php
$content = get_the_content();
$chunks = str_split($content, 500);
//Printing each chunk in a div
foreach($chunks as $chunk_content) {
echo "<div>";
echo $chunk_content;
echo "</div>";
}
?>
More info to str_split: http://www.php.net/manual/en/function.str-split.php
EDIT:
If words should not get cut in the middle, use this function instead:
<?php
$content = get_the_content();
$strings = wordwrap($content, 500, "{BREAK}"); //Put a {BREAK} every 500 characters
$chunks = explode("{BREAK}", $strings); //Put each segment separated by {BREAK} into an array field
//Printing each chunk in a div
foreach($chunks as $chunk_content) {
echo "<div>";
echo $chunk_content;
echo "</div>";
}
?>
If you want to save some memory, you can combine these functions like this:
<?php
foreach(explode("{BREAK}", wordwrap(get_the_content(), 500, "{BREAK}")) as $chunk) {
echo "<div>" . $chunk . "</div>\n"; //The \n creates a new line
}
?>
For more information concerning wordwrap see http://www.php.net/manual/en/function.wordwrap.php

parsing html code and print out

ive this html page ( PART CODE) with multi ( a href="https://twitter.com/$name)
I need to parse all $names and print in page
how i can do this ?
<td>Apr 01 2011<br><b>527
</b>
</td>
<td>
<a href="https://twitter.com/al_rasekhoon" class="twitter-follow-button" data-show count="false" data-lang="" data-width="60px" > al_rasekhoon</a>
</td>
</tr>
<tr class="rowc"><td colspan="11"></td></tr>
You need to loop over your $names array and print a correct a tag for every entry in that array. Like this:
<?php foreach($names as $name){ ?>
<?php echo $name ?>
<?php } ?>
Sounds like screen scraping, and you need to traverse the DOM for this. REs would be very unreliable.
DOMDocument may help you, but you might want to look into a library for screen scraping, such as BeautifulSoup (or some PHP equiv).
If I understand correctly you fetch a html page from somewhere and want to extract all linked twitter users? You can either parse the html code or do this with a bit of string splitting. This code is untested but should give you an idea:
$input = '(the html code)';
$links = explode('<a ', $input); //split input by start of link tags
for ($i = 0; $i < count($links); $i++) {
//cut off everything after the closing '>'
$links[$i] = explode('>', $links[$i], 2)[0]
//skip this link if it doesn't go to twitter.com
if (strpos($links[$i], 'href="twitter.com/') === False) { continue; }
//split by the 'href' attribute and keep everything after 'twitter.com'
$links[$i] = explode('href="twitter.com/', $links[$i], 2)[1]
//cut off everything after the " ending the href attribute
$links[$i] = explode('"', $links[$i], 2)[0]
//now $links[$i] should contain the twitter username
echo $links[$i]
}
Note: if there are other links to twitter on the page that are not the main page or an user, they will get printed too (e.g. if the page links to the twitter FAQ). You would need to filter them manually.
php sucks, let's do this in python!
input = '(the html code)'
links = [l.split(">", 1)[0] for l in input.split("<a ")}
twitter_links = [l for l in links if 'href="twitter.com/' in l]
twitter_hrefs = [l.split('href="twitter.com/', 1)[1] for l in twitter_links]
users = [l.split('"', 1)[0] for l in twitter_hrefs]
print '\n'.join(users)

Categories