How to find which string occuring first in text among multiple strings? - php

I have text like this, "wow! It's Amazing.". I need to split this text by either "!" or "." operator and need to show the first element of array(example $text[0]).
$str="wow! it's, a nice product.";
$text= preg_split('/[!.]+/', $str);
here $text[0] having the value of "wow" only. but I want to know which string occurring first in text (whether its "!" or "."), so that I will append it to $text[0] and shown like this "wow!".
I want to use this preg_split in smarty templates.
<p>{assign var="desc" value='/[!.]+/'|preg_split:'wow! it's, a nice product.'}
{$desc[0]}.</p>
the above code displays the result as "wow". There is no preg_match in smarty, so far i have searched.other wise,i would use that.
Any help would be appreciated.Thanks in Advance.

Instead of preg_split you should use preg_match:
$str="wow! it's, a nice product.";
if ( preg_match('/^[^!.]+[!.]/', $str, $m) )
$s = $m[0]; //=> wow!
If you must use preg_split only then you can do:
$arr = preg_split('/([^!.]+[!.])/', $str, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
$s = $arr[0]; //=> wow!

Try this
/(.+[!.])(.+)/
it will split the string in to two.
$1 => wow!
$2 => it's, a nice product.
see here

Related

PHP: How to preg_split by full stop?

I want to take a string and split it (or explode it) into an array by full-stops (periods).
I used to have:
$processed_data = explode(".", $raw_data);
but this removes the full-stop.
Researching, I found preg_split, so tried:
$processed_data = preg_split('\.', $raw_data, PREG_SPLIT_DELIM_CAPTURE);
with both \. and \\.
but try as I might, I cannot find a way to properly include the full-stop.
Would anyone know the right way to do this?
The expected result is:
The string
$raw_data = 'This is my house. This is my car. This is my dog.';
Is broken into an array by full-stop, eg:
array("This is my house.", "This is my car.", "This is my dog.")
To split a string into sentences:
preg_match_all('~\s*\K[^.!?]*[.!?]+~', $raw_data, $matches);
$processed_data = $matches[0];
Note: if you want to handle edge cases like abbreviations, a simple regex doesn't suffice, you need to use nltk or any other nlp tool with a dictionary.
Can you try this.
$string = preg_replace("/\.\s?([A-Z])/", "*****$1", $raw_data);
$array = explode("*****", $string);

Replace multiple items in a string

i've scraped a html string from a website. In this string it contains multiple strings like color:#0269D2. How can i make str_replace code which replace this string with another color ?
For instance something like this just looping through all color:#0269D in the fulltext string variable?
str_replace("color:#0269D","color:#000000",$fulltext);
you pass array to str_replace function , no need to use loop
$a= array("color:#0269D","color:#000000");
$str= str_replace($a,"", $string);
You have the right syntax. I would add a check:
$newText = str_replace("color:#0269D", "color:#000000", $fulltext, $count);
if($count){
echo "Replaced $count occurrences of 'color'.";
}
This code might be too greedy for what you're looking to do. Careful. Also if the string differs at all, for example color: #0269D, this replacement will not happen.
’str_replace’ already replaces all occurrences of the search string with the replacement string.
If you want to replace all colors but aren't sure which hexcodes you'll find you could use preg_replace to match multiple occurrences of a pattern with a regular expression and replace it.
In your case:
$str = "String with loads of color:#000000";
$pattern = '/color ?: ?#[0-9a-f]{3,6}/i';
$replacement = "color:#FFFFFF";
$result = preg_replace($pattern, $replacement, $str);

Cut string from end to specific char in php

I would like to know how I can cut a string in PHP starting from the last character -> to a specific character. Lets say I have following link:
www.whatever.com/url/otherurl/2535834
and I want to get 2535834
Important note: the number can have a different length, which is why I want to cut out to the / no matter how many numbers there are.
Thanks
In this special case, an url, use basename() :
echo basename('www.whatever.com/url/otherurl/2535834');
A more general solution would be preg_replace(), like this:
<----- the delimiter which separates the search string from the remaining part of the string
echo preg_replace('#.*/#', '', $url);
The pattern '#.*/#' makes usage of the default greediness of the PCRE regex engine - meaning it will match as many chars as possible and will therefore consume /abc/123/xyz/ instead of just /abc/ when matching the pattern.
Use
explode() AND end()
<?php
$str = 'www.whatever.com/url/otherurl/2535834';
$tmp = explode('/', $str);
echo end ($tmp);
?>
Working Demo
This should work for you:
(So you can get the number with or without a slash, if you need that)
<?php
$url = "www.whatever.com/url/otherurl/2535834";
preg_match("/\/(\d+)$/",$url,$matches);
print_r($matches);
?>
Output:
Array ( [0] => /2535834 [1] => 2535834 )
With strstr() and str_replace() in action
$str = 'www.whatever.com/url/otherurl/2535834';
echo str_replace("otherurl/", "", strstr($str, "otherurl/"));
strstr() finds everything (including the needle) after the needle and the needle gets replaced by "" using str_replace()
if your pattern is fixed you can always do:
$str = 'www.whatever.com/url/otherurl/2535834';
$tmp = explode('/', $str);
echo $temp[3];
Here's mine version:
$string = "www.whatever.com/url/otherurl/2535834";
echo substr($string, strrpos($string, "/") + 1, strlen($string));

How to make explode() include the exploded character

$text = "This is /n my text /n wow";
$quotes = explode('/n',$text);
This would split the string into "This is" "My text" "wow"
but I want it to leave the string "/n" as it is, instead of cutting it off,
the output should look like this:
"This is /n" "my text /n" "wow"
Explode your string into an array and then append the separator onto each element of the resulting array.
$sep = "/n";
$text = "This is /n my text /n wow";
$quotes = explode($sep,$text);
$quotes = array_map(function($val) use ($sep) {
return $val . $sep;
}, $quotes);
$last_key = count($quotes)-1;
$quotes[$last_key] = rtrim($quotes[$last_key], $sep);
(Might need to trim($val) as well).
If you have only one possible separator then you can simply append it to the tokens that explode returned. However, if you're asking this question, e.g. because you have multiple possible separators and need to know which one separated two tokens, then preg_split might work for you. E.g. for separators ',' and ';':
$matches = preg_match('/(,|;)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
Have you looked into using the preg_split() function. Per the documentation:
preg_split — Split string by a regular expression
Using this function, apply a positive lookbehind that matches spaces followed by a preceding /n string.
$quotes= preg_split("/(?<=\/n) /", $text);
You can test that this is the desired functionality by doing print_r($quotes); after the above statement. This output from the print_r function will looks similar to the following:
Array ( [0] => This is /n [1] => my text /n [2] => wow )
You may need to use trim() on the values to clear off leading and trailing whitespace but overall it seems to do what you're asking.
DEMO:
If you want to test this functionality out, try copying the following code block and pasting it into the CodeSpace window on http://phpfiddle.org.
<?php
$text = "This is /n my text /n wow";
$values = preg_split("/(?<=\/n) /", $text);
print_r($values);
?>
Select the Run - F9 option to see the output. My apologies for the copy and paste demo example. I couldn't figure out how to create a dedicated URL like some of the other fiddle programs.

Trim string based on certain characters

I've got a string which goes something like myString__sfsdfsf
All I know is that there is a __ somewhere in the string. Content of the string and number of characters is unknown.
I want to remove the __ and all characters that follow so I am left with just myString. How can I achieve this using PHP?
This can be done in several ways. PHP has lots of string functions. You can pick one depending on your requirements. Here are some ways:
Use substr() and strpos():
$str = 'myString__sfsdfsf';
echo substr($str, 0, strpos($str, '__')); // => myString
Or use strtok():
echo strtok($str, '__'); // => myString
Or, maybe even explode():
echo explode('__', $str)[0]; // => myString
You can make use of strpos() and substr():
$str = 'myString__sfsdfsf';
echo substr($str, 0, strpos($str, '__'));
This should be quite fast. However if you need something more fancy than that, you probably want to look into regular expressions, e.g. preg_match().
Use list() and explode():
list($string,) = explode('_', 'myString__sfsdfsf');
echo $string; // Outputs: myString
A str_replace() would also work
$string = str_replace('__', '', $string);
Ignore that, didn't read your question properly

Categories