I have a problem when replacing strings with preg_replace.
function addClass($search, $string) {
return preg_replace("/\b($search)\b/", "<div class=mark>$1</div>", $string);
}
$string = "We won again";
$result = addClass("We", $string);
output ---> <div class=mark>We</div> won again
I want to make $search for multiple strings.
$string = "We won again";
$result = addClass(array("We", "again"), $string);
output ---> <div class=mark>We</div> won <div class=mark>again</div>
How can I create multiple searches, to put strings in an array?
Thanks in advance.
You can use or expresion in regex - (We|again)
function addClass($search, $string) {
return preg_replace("/\b(". implode('|', $search) . ")\b/", "<div class=mark>$1</div>", $string);
}
And, if you want to save the old syntax, make an array from a single string:
function addClass($search, $string) {
if(! is_array($search)) $search = array($search);
return preg_replace("/\b(". implode('|', $search) . ")\b/", "<div class=mark>$1</div>", $string);
}
demo
The alternative solution using is_array and array_map functions:
function addClass($search, $string) {
$search = (is_array($search))? array_map(function($v) { return "/\b($v)\b/"; }, $search) : ["/\b($search)\b/"];
return preg_replace($search, "<div class=mark>$1</div>", $string);
}
Related
function hashTagFinder($str)
{
$hash= explode(" ", substr($str, strpos($str, "#")));
$i=0;
foreach ($hash as $tag) {
$finder=substr_count($tag, "#");
if ($finder>=1 ) {
$fArray = array([$i]=> $tag);
}
$i++;
}
}
I am a beginner and I want to make a hashtag finder function.
I am trying to do it this way but it looks like I can't use object and arrays to define keys.
function convertHashtags($str) {
$regex = "/#+([a-zA-Z0-9_]+)/";
$str = preg_replace($regex, '$0', $str);
return($str);
}
This code return an array with all #hashtags in a string:
$str= 'your string with a #hashtag inside';
preg_match_all('/#\w+/', $str, $match);
var_dump($match); /* print the result */
I have a markdown text content which I have to replace without using library functions.So I used preg replace for this.It works fine for some cases.For cases like heading
for eg Heading
=======
should be converted to <h1>Heading</h1> and also
##Sub heading should be converted to <h2>Sub heading</h2>
###Sub heading should be converted to <h3>Sub heading</h3>
I have tried
$text = preg_replace('/##(.+?)\n/s', '<h2>$1</h2>', $text);
The above code works but I need to have count of hash symbol and based on that I have to assign heading tags.
Anyone help me please....
Try using preg_replace_callback.
Something like this -
$regex = '/(#+)(.+?)\n/s';
$line = "##Sub heading\n ###sub-sub heading\n";
$line = preg_replace_callback(
$regex,
function($matches){
$h_num = strlen($matches[1]);
return "<h$h_num>".$matches[2]."</h$h_num>";
},
$line
);
echo $line;
The output would be something like this -
<h2>Sub heading</h2> <h3>sub-sub heading</h3>
EDIT
For the combined problem of using = for headings and # for sub-headings, the regex gets a bit more complicated, but the principle remains the same using preg_replace_callback.
Try this -
$regex = '/(?:(#+)(.+?)\n)|(?:(.+?)\n\s*=+\s*\n)/';
$line = "Heading\n=======\n##Sub heading\n ###sub-sub heading\n";
$line = preg_replace_callback(
$regex,
function($matches){
//var_dump($matches);
if($matches[1] == ""){
return "<h1>".$matches[3]."</h1>";
}else{
$h_num = strlen($matches[1]);
return "<h$h_num>".$matches[2]."</h$h_num>";
}
},
$line
);
echo $line;
Whose Output is -
<h1>Heading</h1><h2>Sub heading</h2> <h3>sub-sub heading</h3>
Do a preg_match_all like this:
$string = "#####asdsadsad";
preg_match_all("/^#/", $string, $matches);
var_dump ($matches);
And based on count of matches you can do whatever you want.
Or, use the preg_replace_callback function.
$input = "#This is my text";
$pattern = '/^(#+)(.+)/';
$mytext = preg_replace_callback($pattern, 'parseHashes', $input);
var_dump($mytext);
function parseHashes($input) {
var_dump($input);
$matches = array();
preg_match_all('/(#)/', $input[1], $matches);
var_dump($matches[0]);
var_dump(count($matches[0]));
$cnt = count($matches[0]);
if ($cnt <= 6 && $cnt > 0) {
return '<h' . $cnt . ' class="if you want class here">' . $input[2] . '</h' . $cnt . '>';
} else {
//This is not a valid h tag. Do whatever you want.
return false;
}
}
String
"<p>This is </p><p>Stackoverflow</p><p>site for programmers</p>"
Required Output
"This is <p>Stackoverflow</p><p>site for programmers</p>"
Small function
function remove_p($string)
{
$first_p=substr($string,0,3);
$p="<p>";
if($first_p==$p)
{
$string=str_replace('<p>','',$string,$temp=1);
$string=str_replace('</p>','',$string,$temp=1);
}
return $string;
}
But it removes all the <p> </p> tags.Why so?
I am basically writing this to remove the first paragraph tags created by ckeditor.
str_replace acts on all occurrences of a substring, not just the first. You will want to use a different function.
$string = preg_replace('~<p>(.*?)</p>~is', '$1', $string, /* limit */ 1);
To only remove the first <p> and </p> if at the start of the string, add a ^ after the first /.
See also: Using str_replace so that it only acts on the first match?
function replaceFirst($input, $search, $replacement){
$pos = stripos($input, $search);
if($pos === false){
return $input;
}
else{
$result = substr_replace($input, $replacement, $pos, strlen($search));
return $result;
}
}
$string = "This is <p>Stackoverflow</p><p>site for programmers</p>";
echo $string;
echo replaceFirst($string, '<p>', '');
Output:
This is <p>Stackoverflow</p><p>site for programmers</p>
This is Stackoverflow</p><p>site for programmers</p>
Source: #2031045
Hope this helps!
$str = "This is <p>Stackoverflow</p><p>site for programmers</p>";
function remove_p($string)
{
$string=str_replace('<p>','',$string,$temp=1);
$string=str_replace('<\p>','',$string,$temp=1);
return $string;
}
echo(remove_p($str));
The result is:
This is Stackoverflow
site for programmers
Try using the method of this answer.
function remove_p($string)
{
return replaceFirst(replaceFirst($string, '<p>', ''), '</p>', '');
}
Or read about Regular Expressions.
When i search for "bank", it should display Bank-List1, Bank-List2 from the following list.
Railway-List, Bank-List1, Bank-List2, Education, Ecommerce, Articles, Railway-List1.
Is there is any php function to display?
I got the output for exact match. But no result for this type of search.
Please help me to find the solution.
you can use stristr
stristr — Case-insensitive strstr()
<?php // Example from PHP.net
$string = 'Hello World!';
if(stristr($string, 'earth') === FALSE) {
echo '"earth" not found in string';
}
// outputs: "earth" not found in string
?>
So for your situation, if your list was in an array named $values
you could do
foreach($values as $value)
{
if(stristr($value, 'bank') !== FALSE)
{
echo $value."<br>";
}
}
You can do it using stristr. This function returns all of haystack starting from and including the first occurrence of needle to the end. Returns the matched sub-string. If needle is not found, returns FALSE.
Here is the complete code:
<?php
$str="Railway-List, Bank-List1, Bank-List2, Education, Ecommerce, Articles, Railway-List1";
$findme="bank";
$tokens= explode(",", $str);
for($i=0;$i<count($tokens);$i++)
{
$trimmed =trim($tokens[$i]);
$pos = stristr($trimmed, $findme);
if ($pos === false) {}
else
{
echo $trimmed.",";
}
}
?>
DEMO
This solution is only valid for this pattern of text is like: word1, word2, word3
<?php
$text = 'Railway-List, Bank-List1, Bank-List2, Education, Ecommerce, Articles, Railway-List1.';
function search_in_text($word, $text){
$parts = explode(", ", $text);
$result = array();
$word = strtolower($word);
foreach($parts as $v){
if(strpos(strtolower($v), $word) !== false){
$result[] = $v;
}
}
if(!empty($result)){
return implode(", ", $result);
}else{
return "not found";
}
}
echo search_in_text("bank", $text);
echo search_in_text("none", $text);
?>
output:
Bank-List1, Bank-List2
not found
I want to normalize (so canonicalize) a string into the normal form for names:
First letter of the name is uppercase
The difficulty by this is now to follow this rule with second and third name.
My method:
public function namilize($string)
{
$strings = explode(' ', $string);
foreach ($strings as $string) {
$string = ucfirst(strtolower($string));
}
$string = implode(' ', $strings);
return $string;
}
Somehow the
$string = ucfirst(strtolower($string));
fails.
What do I have to correct?
Is there a better way?
Regards
EDIT:
Hi,
thank you all for all the comments and answers.
I found another "modern" method:
public function namilize($string)
{
$string = mb_convert_case($string, MB_CASE_TITLE, mb_detect_encoding($string));
}
When I now would additionally add some regex for Mc and O's than it would be complete :)
public function namilize($name) {
$name = strtolower($name);
$normalized = array();
foreach (preg_split('/([^a-z])/', $name, NULL, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) as $word) {
if (preg_match('/^(mc)(.*)$/', $word, $matches)) {
$word = $matches[1] . ucfirst($matches[2]);
}
$normalized[] = ucfirst($word);
}
return implode('', $normalized);
}
Note that this will work for names like John O'Brian, James McManus, etc. For other names with prefixes like McManus, simply add the prefix to the preg_match(). Obviously, this runs the possibility of false positives, but no method is going to be 100% foolproof.
You have to pass the $string by reference, note the &:
public function namilize($string)
{
$strings = explode(' ', $string);
foreach ($strings as &$string) {
$string = ucfirst(strtolower($string));
}
$string = implode(' ', $strings);
return $string;
}
Or use the function suggested by #thetaiko ucwords($string)
The $string inside the foreach will only store the last iteration (or the last name). This doesn't really matter though because the variable in the foreach is never used for output. The implode just undoes what you did with the explode so you will end up with the exact same output as the input. I changed the variable names to be more descriptive in this example:
function namilize($name_in)
{
$a_names = explode(' ', $name_in); //explode string into array
foreach ($a_names as $name) {
$a_fullname[] = ucfirst(strtolower($name)); //build array of proper case names
}
$string = implode(' ', $a_fullname); //convert array into string
return $string;
}