PHP regex split text to insert HTML - php

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 :)

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.

Multiple answer with preg_replace

I have a problem with preg_replace in PHP.
My text:
[Derp] a
• [Derp] a
My regex:
$simple_search[0] = '/\[(.*?)\] (.*?)/is';
$simple_search[1] = '/\• \[(.*?)\] (.*?)/is';
My subject:
$simple_replace[0] = "[color=#009D9D][$1][/color] $2";
$simple_replace[1] = "[color=#30BA76]• [$1][/color] [color=#92CF91]$2[/color]";
After preg_replace:
[color=#009D9D][Derp][/color] a
[color=#30BA76]#color=#009D9D][Derp][/color[/color] [color=#606090]: [/color]a
(it's a tool for coloring quotes)
[Derp] a and
• [Derp] a must not have the same color.
The problem is that the first search then replaces that this is not the right thing.
How can I detect that research is equal to the string?
replace your first regexp:
/(?<!\• )\[(.*?)\] (.*?)/is
means can not have front of the "[" an "•" and a space. Also if the • stands in beginning of your lines then you could put ^ front of it
$str = '[Derp] a
• [Derp] a';
$simple_search[0] = '/(\• )?(?P<m2>\[.*?\]) (?P<m3>.*)/i';
echo $str = preg_replace_callback($simple_search[0],
function ($m) {
if (!$m[1]) return '[color=#009D9D]' . $m[2] . '[/color] ' . $m[3];
else return '[color=#30BA76]• ' . $m[2] . '[/color] [color=#92CF91]' . $m[3] . '[/color]';
}, $str
);
result
[color=#009D9D][Derp][/color] a
[color=#30BA76]• [Derp][/color] [color=#92CF91]a[/color]

Preg Relplace only replace instances of text with a trailing space

I have a preg_replace question. I am using preg_replace to generate contextual links in text blocks using the following code:
$contextualLinkStr = 'mytext';
$content = 'My text string which includes MYTEXT in various cases such as Mytext and mytext. However it also includes image tags such as <img src="http://www.myurl.com/mytext-1.jpg">';
$content = preg_replace('/' . $contextualLinkStr . '/i', '\\0', $content);
The preg_replace is working well on the text and generating the relevant links while retaining case but it's also generating a link within the URL of the image tag. I was thinking If I simply added a trailing space to the expression in the preg_replace function it would fix it due to the fact that all text instances will have a trailing space whereas no image urls will, as follows:
$content = preg_replace('/' . $contextualLinkStr . '/i' . ' ', '\\0' . ' ', $content);
But this doesn't work. Can anybody tell me how I make the trailing space a condition of the match?
Thanks in advance.
Jason.
I've just worked it out guys. I was being daft. For reference the relevant code is:
$content = preg_replace('/' . $contextualLinkStr . ' /i', '\\0 ', $content);
Thanks.

Merging preg_match_all and preg_replace

I have some code running which finds out hashtags in the string and turns them into links. I have done this using preg_match_all as shown below:
if(preg_match_all('/(#[A-z_]\w+)/', $postLong, $arrHashTags) > 0){
foreach ($arrHashTags[1] as $strHashTag) {
$long = str_replace($strHashTag, ''.$strHashTag.'', $postLong);
}
}
Also, for my search script, I need to bold the searched keywords in the result string. Something similar to the below code using preg_replace:
$string = "This is description for Search Demo";
$searchingFor = "/" . $searchQuery . "/i";
$replacePattern = "<b>$0<\/b>";
preg_replace($searchingFor, $replacePattern, $string);
The problem that I am having is that both have to work together and should be thrown as a combined result. One way I can think of is to run the resultant string from preg_match_all with the preg_replace code but what if the tags and the searched string are the same? The second block will bold my tag as well which is not desired.
update the code i'm running based on the answer given below but it still doesn't work
if(preg_match_all('/(#[A-z_]\w+)/', $postLong, $arrHashTags) > 0){
foreach ($arrHashTags[1] as $strHashTag) {
$postLong = str_replace($strHashTag, ''.$strHashTag.'', $postLong);
}
}
And immediately after this, i run this
$searchingFor = "/\b.?(?<!#)" . $keystring . "\b/i";
$replacePattern = "<b>$0<\/b>";
preg_replace($searchingFor, $replacePattern, $postLong);
Just so you know, this is all going inside a while loop, which is generating the list
You just need to modify you the search pattern to avoid ones that start with a '#'
$postLong = "This is description for Search Demo";
if(preg_match_all('/(#[A-z_]\w+)/', $postLong, $arrHashTags) > 0){
foreach ($arrHashTags[1] as $strHashTag) {
$postLong = str_replace($strHashTag, ''.$strHashTag.'', $postLong);
}
}
# This expression finds any text with 0 or 1 characters in front of it
# and then does a negative look-behind to make sure that the character isn't a #
searchingFor = "/\b.?(?<!#)" . $searchQuery . "\b/i";
$replacePattern = "<b>$0<\/b>";
preg_replace($searchingFor, $replacePattern, $postLong);
Or if you don't need an array of the available hashes for another reason, you could use preg_replace only.
$postLong = "This is description for #Search Demo";
$patterns = array('/(#[A-z_]\w+)/', "/\b.?(?<!#)" . $searchQuery . "\b/i");
$replacements = array(''.$0.'', ' "<b>$0<\/b>');
preg_replace($patterns, $replacements, $postLong);

How do I split a Wordpress title at the – in PHP?

I am working on my Wordpress blog and its required to get the title of a post and split it at the "-". Thing is, its not working, because in the source its &ndash and when I look at the result on the website, its a "long minus" (–). Copying and pasting this long minus into some editor makes it a normal minus (-). I cant split at "-" nor at &ndash, but somehow it must be possible. When I created the article, I just typed "-" (minus), but somewhere it gets converted to – automatically.
Any ideas?
Thanks!
I think I found it. I remember that I have meet the similar problem that when I paste code in my post the quote mark transform to an em-quad one when display to readers.
I found that is in /wp-include/formatting.php line 56 (wordpress ver 3.3.1), it defined some characters need to replace
$static_characters = array_merge( array('---', ' -- ', '--', ' - ', 'xn–', '...', '``', '\'\'', ' (tm)'), $cockney );
$static_replacements = array_merge( array($em_dash, ' ' . $em_dash . ' ', $en_dash, ' ' . $en_dash . ' ', 'xn--', '…', $opening_quote, $closing_quote, ' ™'), $cockneyreplace );
and in line 85 it make an replacement
// This is not a tag, nor is the texturization disabled static strings
$curl = str_replace($static_characters, $static_replacements, $curl);
If you want to split a string at the "-" character, basically you must replace "-" with a space.
Try this:
$string_to_be_stripped = "my-word-test";
$chars = array('-');
$new_string = str_replace($chars, ' ', $string_to_be_stripped);
echo $new_string;
These lines splits the string at the "-". For example, if you have my-word-test, it will echo "my word test". I hope it helps.
For more information about the str_replace function click here.
If you want to do this in a WordPress style, try using filters. I suggest placing these lines in your functions.php file:
add_filter('the_title', function($title) {
$string_to_be_stripped = $title;
$chars = array('-');
$new_string = str_replace($chars, ' ', $string_to_be_stripped);
return $new_string;
})
Now, everytime you use the_title in a loop, the title will be escaped.

Categories