remove substring from string by entering first and last character php - php

How can i remove substring from string by entering first and last character of substring in php
For example in string "Hello my name is John" if i enter 'n' and 's' it should return "Hello my John"... Please Help

/**
* Process function.
* For lack of a better name.
*/
function process($f, $l, $subject)
{
return preg_replace(sprintf('/%s.*?%s/', preg_quote($f), preg_quote($l)), '', $subject);
}
$f = 'n';
$l = 's';
echo process($f, $l, 'Hello my last name is Doe and my first name is John');
Output:
Hello my last Doe at John
I added utility, but it is effectively the same as preg_replace('/n.*?s/', '', $subject).

with your string given:
$var = "Hello my name is John";
$sub = getSubString($var,"n","s");
echo $sub;
function getSubString($str,$start,$end) {
if(($pos1=strpos($str,$start))===false)
return $str; // not found
if(($pos2=strpos($str,$end,$pos1))===false)
return $str; // not found
return substr($str,0,$pos1).substr($str,$pos2+1);
}
results in:
Hello my John

You should get the position of the first and second letter and use strpos for the method substr
function my_Cut($string, $first_letter, $second_letter){
$pos[] = strpos($string, $first_letter);
$pos[] = strpos($string, $second_letter);
$result = substr($string, $pos[0] , -($pos[1]-$pos[0]-2));
return str_replace ($result, "", $string);
}
$string = "Hello my name is John";
echo my_Cut($string, "n", "s");
Something like this... I think.

Related

How to find out if there is any redundant word in string in php?

I need to find out if there are any redundant words in string or not .Is there any function that can provide me result in true/false.
Example:
$str = "Hey! How are you";
$result = redundant($str);
echo $result ; //result should be 0 or false
But for :
$str = "Hey! How are are you";
$result = redundant($str);
echo $result ; //result should be 1 or true
Thank you
You could use explode to generate an array containing all words in your string:
$array = explode(" ", $str);
Than you could prove if the arrays contains duplicates with the function provided in this answer:
https://stackoverflow.com/a/3145660/5420511
I think this is what you are trying to do, this splits on punctuation marks or whitespaces. The commented out lines can be used if you want the duplicated words:
$str = "Hey! How are are you?";
$output = redundant($str);
echo $output;
function redundant($string){
$words = preg_split('/[[:punct:]\s]+/', $string);
if(max(array_count_values($words)) > 1) {
return 1;
} else {
return 0;
}
//foreach(array_count_values($words) as $word => $count) {
// if($count > 1) {
// echo '"' . $word . '" is in the string more than once';
// }
//}
}
References:
http://php.net/manual/en/function.array-count-values.php
http://php.net/manual/en/function.max.php
http://php.net/manual/en/function.preg-split.php
Regex Demo: https://regex101.com/r/iH0eA6/1

Use a regex match as an array pointer

I want to replace some numbers in a string with the content of the array in the position which this number points to.
For example, replace "Hello 1 you are great", with "Hello myarray[1] you are great"
I was doing the next: preg_replace('/(\d+)/','VALUE: ' . $array[$1],$string);
But it does not work. How could I do it?
You should use a callback.
<?php
$str = 'Hello, 1!';
$replacements = array(
1 => 'world'
);
$str = preg_replace_callback('/(\d+)/', function($matches) use($replacements) {
if (array_key_exists($matches[0], $replacements)) {
return $replacements[$matches[0]];
} else {
return $matches[0];
}
}, $str);
var_dump($str); // 'Hello, world!'
Since you are using a callback, in the event that you actually want to use a number, you might want to encode your strings as {1} or something instead of 1. You can use a modified match pattern:
<?php
// added braces to match
$str = 'Hello, {1}!';
$replacements = array(
1 => 'world'
);
// added braces to regex
$str = preg_replace_callback('/\{(\d+)\}/', function($matches) use($replacements) {
if (array_key_exists($matches[1], $replacements)) {
return $replacements[$matches[1]];
} else {
// leave string as-is, with braces
return $matches[0];
}
}, $str);
var_dump($str); // 'Hello, world!'
However, if you are always matching known strings, you may want to use #ChrisCooney's solution because it offers less opportunity to screw up the logic.
The other answer is perfectly fine. I managed it this way:
$val = "Chris is 0";
// Initialise with index.
$adj = array("Fun", "Awesome", "Stupid");
// Create array of replacements.
$pattern = '!\d+!';
// Create regular expression.
preg_match($pattern, $val, $matches);
// Get matches with the regular expression.
echo preg_replace($pattern, $adj[$matches[0]], $val);
// Replace number with first match found.
Just offering another solution to the problem :)
$string = "Hello 1 you are great";
$replacements = array(1 => 'I think');
preg_match('/\s(\d)\s/', $string, $matches);
foreach($matches as $key => $match) {
// skip full pattern match
if(!$key) {
continue;
}
$string = str_replace($match, $replacements[$match], $string);
}
<?php
$array = array( 2 => '**', 3 => '***');
$string = 'lets test for number 2 and see 3 the result';
echo preg_replace_callback('/(\d+)/', 'replaceNumber', $string);
function replaceNumber($matches){
global $array;
return $array[$matches[0]];
}
?>
output
lets test for number ** and see *** the result

How to create a function that can transform the last word into Uppercases?

How do i create a function replaceMe() in php that would turn:
$str = 'This is a very long string';
into:
'This is a very long STRING?'
can someone help me?
You apparently want to do a regular expression substitution, anchored at the end of the line. Use preg_replace:
$str = 'This is a very long string';
# This is a very long LINE
echo preg_replace("/string$/", "LINE", $str);
For a general case, you can provide a callback instead of a replacement string, and simply uppercase the matched substring with preg_replace_callback:
$str = 'This is a very long blah';
function word_to_upper($match) {
return strtoupper($match[1]);
}
# This is a very long BLAH
echo preg_replace_callback("/(\w+)$/", "word_to_upper", $str);
If you're using PHP 5.4 or greater, you can supply the callback as an anonymous function:
echo preg_replace_callback("/(\w+)$/", function ($match) {
return strtoupper($match[1])
}, $str);
This works:
$str = 'This is a very long string';
echo $str."<br/>";
function replaceMe($str = "")
{
$words = explode(" ",$str);
$totalwords = count($words)-1;
$lastword = $words[$totalwords];
$words[$totalwords] = strtoupper($lastword);
$str = implode(" ",$words);
return $str;
}
echo replaceMe($str);
?>
Output:
This is a very long string
This is a very long STRING
$str = 'This is a very long string.';
function lastWordUpper($str){
$temp = strrev($str);
$last = explode(" ", $temp, 2);
return strrev(strtoupper($last[0]). ' ' .$last[1]) ;
}
echo lastWordUpper($str);

How to uppercase first letter after a hyphen, ie Adam Smith-Jones

I'm looking for a way to uppercase the first letter/s of a string, including where the names are joined by a hyphen, such as adam smith-jones needs to be Adam Smith-Jones.
ucwords() (or ucfirst() if I split them into firstname, lastname) only does Adam Smith-jones
$string = implode('-', array_map('ucfirst', explode('-', $string)));
What do you think about the following code ?
mb_convert_case(mb_strtolower($value, "UTF-8"), MB_CASE_TITLE, "UTF-8");
Please note that this also handles accented characters (usefull for some languages such as french).
Is this ok ?
function to_upper($name)
{
$name=ucwords($name);
$arr=explode('-', $name);
$name=array();
foreach($arr as $v)
{
$name[]=ucfirst($v);
}
$name=implode('-', $name);
return $name;
}
echo to_upper("adam smith-jones");
Other way:
<?php
$str = 'adam smith-jones';
echo preg_replace("/(-)([a-z])/e","'\\1'.strtoupper('\\2')", ucwords($str));
?>
/**
* Uppercase words including after a hyphen
*
* #param string $text lower-case text
* #return string Upper-Case text
*/
function uc_hyphenated_words($text)
{
return str_replace("- ","-",ucwords(str_replace("-","- ",$text)));
}
<?php
// note - this does NOT do what you want - but I think does what you said
// perhaps you can modify it to do what you want - or we can help if you can
// provide a bit more about the data you need to update
$string_of_text = "We would like to welcome Adam Smith-jones to our 3rd, 'I am addicted to stackoverflow-posting' event.";
// both Smith-Jones and Stackoverflow-Posting should result
// may be wrong
$words = explode(' ',$string_of_text);
foreach($words as $index=>$word) {
if(false !== strpos('-',$word)) {
$parts = explode('-',$word);
$newWords = array;
foreach($parts as $wordIndex=>$part) {
$newWords[] = ucwords($part);
}
$words[$index] = implode('-',$newWords);
}
}
$words = implode(' ',$words);
?>
Something akin to this - untested - for the purposes of making sure I understand the question.
You can us 'ucwords' to capitalize all words at once, and 'implode' and 'explode' together, like this:
ucwords(implode(" ", explode("_", "my_concatinated_word_string")));
function capWords($string) {
$string = str_replace("-", " - ", $string);
$string = ucwords(strtolower($string));
$string = str_replace(" - ", "-", $string);
return $string;
}
Here is a simple function that can convert all the words in a string to title case:
function toTitleCase($string) {
return preg_replace_callback('/\w+/', function ($match) {
return ucfirst(strtolower($match[0]));
}, $string);
}

highlight the word in the string, if it contains the keyword

how write the script, which menchion the whole word, if it contain the keyword? example: keyword "fun", string - the bird is funny, result - the bird is * funny*. i do the following
$str = "my bird is funny";
$keyword = "fun";
$str = preg_replace("/($keyword)/i","<b>$1</b>",$str);
but it menshions only keyword. my bird is funny
Try this:
preg_replace("/\w*?$keyword\w*/i", "<b>$0</b>", $str)
\w*? matches any word characters before the keyword (as least as possible) and \w* any word characters after the keyword.
And I recommend you to use preg_quote to escape the keyword:
preg_replace("/\w*?".preg_quote($keyword)."\w*/i", "<b>$0</b>", $str)
For Unicode support, use the u flag and \p{L} instead of \w:
preg_replace("/\p{L}*?".preg_quote($keyword)."\p{L}*/ui", "<b>$0</b>", $str)
You can do the following:
$str = preg_replace("/\b([a-z]*${keyword}[a-z]*)\b/i","<b>$1</b>",$str);
Example:
$str = "Its fun to be funny and unfunny";
$keyword = 'fun';
$str = preg_replace("/\b([a-z]*${keyword}[a-z]*)\b/i","<b>$1</b>",$str);
echo "$str"; // prints 'Its <b>fun</b> to be <b>funny</b> and <b>unfunny</b>'
<?php
$str = "my bird is funny";
$keyword = "fun";
$look = explode(' ',$str);
foreach($look as $find){
if(strpos($find, $keyword) !== false) {
if(!isset($highlight)){
$highlight[] = $find;
} else {
if(!in_array($find,$highlight)){
$highlight[] = $find;
}
}
}
}
if(isset($highlight)){
foreach($highlight as $replace){
$str = str_replace($replace,'<b>'.$replace.'</b>',$str);
}
}
echo $str;
?>
Here by am added multi search in a string for your reference
$keyword = ".in#.com#dot.com#1#2#3#4#5#6#7#8#9#one#two#three#four#five#Six#seven#eight#nine#ten#dot.in#dot in#";
$keyword = implode('|',explode('#',preg_quote($keyword)));
$str = "PHP is dot .com the amazon.in 123455454546 dot in scripting language of choice.";
$str = preg_replace("/($keyword)/i","<b>$0</b>",$str);
echo $str;
Basically, since this is HTML, what you have to do is iterate over text nodes and split those containing the search string into up to three nodes (before match, after match and the highlighted match). If "after match" node exist, it must be processed too. Here is a PHP7 example using PHP DOM extension. The following function accepts preg_quoted UTF-8 search string (or regex-conpatible expression like apple|orange). It will enclose every match in a given tag with a given class.
function highlightTextInHTML($regex_compatible_text, $html, $replacement_tag = 'span', $replacement_class = 'highlight') {
$d = new DOMDocument('1.0','utf-8');
$d->loadHTML('<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/></head>' . $html);
$xpath = new DOMXPath($d);
$process_node = function(&$node) use($regex_compatible_text, $replacement_tag, $replacement_class, &$d, &$process_node) {
$i = preg_match("~(?<before>.*?)(?<search>($regex_compatible_text)+)(?<after>.*)~ui", $node->textContent, $m);
if($i) {
$x = $d->createElement($replacement_tag);
$x->setAttribute('class', $replacement_class);
$x->textContent = $m['search'];
$parent_node = $node->parentNode;
$before = null;
$after = null;
if(!empty($m['after'])) {
$after = $d->createTextNode($m['after']);
$parent_node->replaceChild($after, $node);
$parent_node->insertBefore($x, $after);
} else {
$parent_node->replaceChild($x, $node);
}
if(!empty($m['before'])) {
$before = $d->createTextNode($m['before']);
$parent_node->insertBefore($before, $x);
}
if($after) {
$process_node($after);
}
}
};
$node_list = $xpath->query('//text()');
foreach ($node_list as $node) {
$process_node($node);
}
return preg_replace('~(^.*<body>)|(</body>.*$)~mis', '', $d->saveHTML());
}
Search and highlight the word in your string, text, body and paragraph:
<?php $body_text='This is simple code for highligh the word in a given body or text'; //this is the body of your page
$searh_letter = 'this'; //this is the string you want to search for
$result_body = do_Highlight($body_text,$searh_letter); // this is the result with highlight of your search word
echo $result_body; //for displaying the result
function do_Highlight($body_text,$searh_letter){ //function for highlight the word in body of your page or paragraph or string
$length= strlen($body_text); //this is length of your body
$pos = strpos($body_text, $searh_letter); // this will find the first occurance of your search text and give the position so that you can split text and highlight it
$lword = strlen($searh_letter); // this is the length of your search string so that you can add it to $pos and start with rest of your string
$split_search = $pos+$lword;
$string0 = substr($body_text, 0, $pos);
$string1 = substr($body_text,$pos,$lword);
$string2 = substr($body_text,$split_search,$length);
$body = $string0."<font style='color:#FF0000; background-color:white;'>".$string1." </font> ".$string2;
return $body;
} ?>

Categories