Split variable content into multiple paragraphs - php

Hey there,
I have this little php code:
<p class="category_text"><? echo $category_text; ?></p>
I waht to split the $category_text and get something like this:
This is sentence 1 of category_text
This is sentence 2 of category_text
and so on...
$category_text has about 300 words and lets say 6 sentences. How could I split the text in multiple paragraphs (delimited by the stop sings ".")
Thank you very much!

echo '<p class="category_text">'
. implode('</p><p class="category_text">', explode('.',$string))
.'</p>';

You can just replace the "." by the tag "":
<p class="category_text"><? echo str_replace('.', '.<br />', $category_text); ?></p>
It's not a perfect solution! But if you text is simple enough this little trick should work.
For example if you have a line with 3 dots:
$category_text = "Ok...";
It will show up like that:
OK.
.
.
Also if your sentences finish by "?" or "!" you can also use that:
<p class="category_text"><? echo str_replace(array('.', '!', '?'), array('.<br />', '!<br />', '?<br />'), $category_text); ?></p>
PS: My solution will create one paragraph "" but with multiple line break

Try creating an array, and then output the lines one by one. A sentence ending in ... would still be recognized as still ends in ". ".
$sentences = explode('. ', $category_text)
foreach($sentences as $val)
{
echo $val . ".<br /><br />";
}

You want to split a text into sentences, which is not trivial - using explode(".", $string) does often not give good results.
Search Stackoverflow for "php split sentence", or directly try the solution to PHP: Parse document / text into sentences :
http://www.zubrag.com/scripts/text-splitter.php
Once you have an array with sentences, use
echo '<p>' . implode('</p><p>', $sentences) . '</p>';
to echo them out.

Related

Replacing the SPACE at first and last

I want to replace the first and last words and sentences .
I use this code.
$text = ' this is the test for string. ';
echo $text = str_replace(" ", "", $text);
when i have use replace code .
all space is deleted and repalsed.
any body can help me?!
i want get this:
this is the test for string.
You probably want the trim function here:
$text = ' this is the test for string. ';
echo '***' . trim($text) . '***';
***this is the test for string.***
Just to round out this answer, if you wanted to accomplish the same thing using a replacement, you could do a regex replace as follows:
$out = preg_replace("/^\s*|\s*$/", "", $text);
echo '***' . $out . '***';
***this is the test for string.***
This approach might a good starting point if you wanted to do a regex replacement with perhaps slightly different logic.

How to preg_replace links so that the hash is kept

I have huge online php fileset that is made dynamically.
It has links, even some invalid ones with quotes (made with frontpage)
index2.php?page=xd
index2.php?page=xj asdfa
index2.php?page=xj%20aas
index2.php?page=xj#jumpword
index2.php?page=gj#jumpword with spaces that arenot%20
index2.php?page=afdsdj#jumpword%20with
index2.php?page=xj#jumpword with "quotes" iknow
$input_lines=preg_replace("/(index2.php?page\=.*)(#[a-zA-Z0-9_ \\"]*)(\"\>)/U", "$0 --> $2", $input_lines);
I want all of those to be just with the # -part and not have the index2.php?page=* part.
I could not get this to work in whole evening. So please help.
In some cases, you can use parse_url to get attributes from the URL (ex: what is after the #), like so:
$urls = array(
'index2.php?page=xd',
'index2.php?page=xj asdfa',
'index2.php?page=xj%20aas',
'index2.php?page=xj#jumpword',
'index2.php?page=gj#jumpword with spaces that arenot%20',
'index2.php?page=afdsdj#jumpword%20with',
'index2.php?page=xj#jumpword with "quotes" iknow',
);
foreach($urls as $url){
echo 'For "' . $url . '": ';
$parsed = parse_url($url);
echo isset($parsed['fragment']) ? $parsed['fragment'] : 'DID NOT WORK';
echo '<br>';
}
Output:
For "index2.php?page=xd": DID NOT WORK
For "index2.php?page=xj asdfa": DID NOT WORK
For "index2.php?page=xj%20aas": DID NOT WORK
For "index2.php?page=xj#jumpword": jumpword
For "index2.php?page=gj#jumpword with spaces that arenot%20": jumpword with spaces that arenot%20
For "index2.php?page=afdsdj#jumpword%20with": jumpword%20with
For "index2.php?page=xj#jumpword with "quotes" iknow": jumpword with "quotes" iknow

Case (in)sensitive Replace for str_ireplace for search results

I have a list of items. I want to use them in search terms. Say the list is:
Hello, World!
The World is not Enough
Around the world in 80 days.
WAR of the WORLDS
Now, if I am searching for the keyword world (notice all are in small letters), I am giving this function.
preg_replace(/world/, '<span class="label label-search-results">$0</span>', $item);
Where the $item is each line, the output is:
Warning: preg_replace() [function.preg-replace]: Delimiter must not be alphanumeric or backslash in /myfile.php on line XX.
If I use str_ireplace(), I don't know the original case of the found text. It would be something like:
str_ireplace("world", '<span class="label label-search-results">world</span>', $item);
And that results in all the world, World and WORLD being in lower case. Any ideas on how to preserve the case after replace?
That's the perfect use case for preg_replace_callback(), just use it like this:
echo preg_replace_callback("/" . preg_quote($_GET["q"], "/") . "/i", function($m){
return "<span class='label label-search-results'>" . $m[0] . "</span>";
}, $item);
preg_replace('/(world)/i', '<span class="label label-search-results">$1</span>', $item);
Try with the flag i for case-insensitivity.

PHP regex split text to insert HTML

Very(!) new to regex but...
I have the following text strings outputted from a $title variable:
A. This is a title
B. This is another title
etc...
I'm after the following:
<span>A.</span> This is a title
<span>B.</span> This is another title
etc...
Currently I have the following code:
$title = $element['#title'];
if (preg_match("([A-Z][\.])", $title)) {
return '<li' . drupal_attributes($element['#attributes']) . ">Blarg</li>\n";
} else {
return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}
This replaces anything A. through to Z. with Blarg however I'm not sure how to progress this?
In the Text Wrangler app I could wrap regex in brackets and output each argument like so:
argument 1 = \1
argument 2 = \2
etc...
I know I need to add an additional regex to grab the remainder of the text string.
Perhaps a regex guru could help and novice out!
Thanks,
Steve
Try
$title = 'A. This is a title';
$title = preg_replace('/^[A-Z]\./', '<span>$0</span>', $title);
echo $title;
// <span>A.</span> This is a title
If the string contains newlines and other titles following them, add the m modifier after the ending delimiter.
If the regex doesn't match then no replacements will be made, so there is no need for the if statement.
Is it always just 2 char ("A.", "B.", "C.",...)
because then you could work with a substring instead of regex.
Just pick of the first 2 chars of the link and wrap the span around the substring
Try this (untested):
$title = $element['#title'];
if (preg_match("/([A-Z]\.)(.*)/", $title, $matches)) {
return '<li' . drupal_attributes($element['#attributes']) . "><span>{$matches[0]</span>{$matches[1]}</li>\n";
} else {
return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}
The change here was to first add / to the start and end of the string (to denote it's a regex), then remove the [ and ] around the period . because that's just a literal character on its own, then to add another grouping which will match the rest of the string. I also Added a $matches to preg_match() to place these two matches in to to use later, which we do on the next life.
Note: You could also do this instead:
$title = preg_replace('/^([A-Z]\.)/', "<span>$1</span>", $title);
This will simply replace the A-Z followed by the period at the start of the string (denoted with the ^ character) with <span>, that character (grabbed with the brackets) and </span>.
Again, that's not tested, but should give you a headstart :)

preg_replace between > and <

I have this:
<div> 16</div>
and I want this:
<div><span>16</span></div>
Currently, this is the only way I can make it work:
preg_replace("/(\D)(16)(\D)/", "$1<span>$2</span>$3", "<div> 16</div>")
If I leave off the $3, I get:
<div><span>16</span>/div>
Not quite sure what your after, but the following is more generic:
$value = "<div> 16 </div>";
echo(preg_replace('%(<(\D+)[^>]*>)\s*([^\s]*)\s*(</\2>)%', '\1<span>\3</span>\4', $value));
Which would result in:
<div><span>16</span></div>
Even if the value were:
<p> 16 </div>
It would result in:
<p><span>16</span></p>
I think you meant to say you're using the following:
print preg_replace("/(\\D+)(16)(\\D+)/", "$1<span>$2</span>$3", "<div>16</div>");
There's nothing wrong with that. $3 is going to contain everything matched in the second (\D+) group. If you leave it off, obviously it's not going to magically appear.
Note that your code in the question had some errors:
You need to escape your \'s in a string.
You need to use \D+ to match multiple characters.
You have a space before 16 in your string, but you're not taking this into account in your regex. I removed the space, but if you want to allow for it you should use \s* to match any number of whitespace characters.
The order of your parameters was incorrect.
Try following -
$str = "<div class=\"number\"> 16</div>";
$formatted_str = preg_replace("/(<div\b[^>]*>)(.*?)<\/div>/i", "$1<span>$2</span></div>", $s);
echo $formatted_str;
This is what ended up working the best:
preg_replace('/(<.*>)\s*('. $page . ')\s*(<.*>)/i', "$1" . '<span class="curPage">' . "$2" . '</span>' . "$3", $pagination)
What I found was that I didn't know for sure what tags would precede or follow the page number.

Categories