Get text in quotes - php

is there is some function that can take just text inside the quotes from the variable?
Just like:
$text = 'I am "pro"';
echo just_text_in_quotes($text);
I know that this function doesn't exist.. but I need something like that.
I was thinking about fnmatch("*",$text)
But this cant Echo just that text, It's just for check.
Can you please help me?
Thank you.

This function will return the first matched text between quotes (possibly an empty string).
function just_text_in_quotes($str) {
preg_match('/"(.*?)"/', $str, $matches);
return isset($matches[1]) ? $matches[1] : FALSE;
}
You could modify it to return an array of all matches, but in your example you use it within the context of echoing its returned value. Had it returned an array, all you would get is Array.
You may be better off writing a more generic function that can handle multiple occurrences and a custom delimiter.
function get_delimited($str, $delimiter='"') {
$escapedDelimiter = preg_quote($delimiter, '/');
if (preg_match_all('/' . $escapedDelimiter . '(.*?)' . $escapedDelimiter . '/s', $str, $matches)) {
return $matches[1];
}
}
This will return null if no matches were found.

preg_match is made for this
preg_match('/"(.*?)"/', $str, $quoted_string);
echo "<pre>"; print_r($quoted_string);
//return array of all quoted words in $str

This regex:
"(\w*)"
will help you as you can see here: http://rubular.com/r/3kgH7NdtLm

Related

Find part of a string and output the whole string

I would like to find part of a string and if true I want to ouput the whole of the string that it finds.
Below is an example:
$Towns = "Eccleston, Aberdeen, Glasgow";
$Find = "Eccle";
if(strstr($Find, $Towns)){
echo outputWholeString($Find, $Towns); // Result: Eccleston.
}
If anyone can shed some light on how to do this as well, and bare in mind that it will not be static values; the $Towns and $Find variables will be dynamically assigned on my live script.
Use explode() and strpos() as
$Towns = "Eccleston, Aberdeen, Glasgow";
$data=explode(",",$Towns);//
$Find = "Eccle";
foreach ($data as $town)
if (strpos($town, $Find) !== false) {
echo $town;
}
DEMO
You have to use strpos() to search for a string inside another one:
if( strpos($Towns, $Find) === false ) {
echo $Towns;
}
Note that you have to use "===" to know if strpos() returned false or 0.
The solution using preg_match function:
$Towns = "Eccleston, Aberdeen, Glasgow";
$Find = "Eccle";
preg_match("/\b\w*?$Find\w*?\b/", $Towns, $match);
$result = (!empty($match))? $match[0] : "";
print_r($result); // "Eccleston"
Assuming that you will always have $Towns separated by ", " then you could do something like this
$Towns = "Eccleston, Aberdeen, Glasgow";
$Find = "Eccle";
$TownsArray = explode(", ", $Towns);
foreach($TownsArray as $Town)
{
if(stristr($Find, $Town))
{
echo $Town; break;
}
}
The above code will output the Town once it finds the needle and exit the foreach loop. You could remove the "break;" to continue letting the script run to see if it finds more results.
Using preg_match(), it is possible to search for Eccle and return the Eccleston word.
I use the Pearl Compatible Regular Expression (PCRE) '#\w*' . $Find . '\w*#' in the code below and the demo code.
The # characters are PCRE delimiters. The pattern searched is inside these delimiters. Some people prefer / as delimiter.
The \w indicates word characters.
The * indicates 0 or more repetions of the previous character.
So, the #\w*Eccle\w*# PCRE searches for an string containing Eccle surrounded by one or more word characters (letters)
<?php
$Towns = "Eccleston, Aberdeen, Glasgow";
$Find = "Eccle";
if (preg_match('#\w*' . $Find . '\w*#', $Towns, $matches)) {
print_r($matches[0]);
}
?>
Running code: http://sandbox.onlinephpfunctions.com/code/4e4026cbbd93deaf8fef0365a7bc6cf6eacc2014
Note: '#\w*' . $Find . '\w*#' is the same as "#\w*$Find\w*#" (note the surrounding single or double quotes). See this.
You were nearly there...
This is probably what you are looking for:
<?php
$Towns = "Eccleston, Aberdeen, Glasgow";
$Find = "Eccle";
if(stripos($Towns, $Find)) {
echo $Towns;
}
The output is: Eccleston, Aberdeen, Glasgow which is what I would call "the whole string".
If however you only want to output that partly matched part of "the whole string", then take a look at that example:
<?php
$Towns = "Eccleston, Aberdeen, Glasgow";
$Find = "Eccle";
foreach (explode(',', $Towns) as $Town) {
if(stripos($Town, $Find)) {
echo trim($Town);
}
}
The output of that obviously is: Eccleston...
Two general remarks:
the strpos() / stripos() functions are better suited here, since they return only a position instead of the whole matched string which is enough for the given purpose.
the usage of stripos() instead of strpos() performs a case insensitive search, which probably makes sense for the task...

Replace all occurrences of \\ not starting with

This should be simple. I want to change all of these substrings:
\\somedrive\some\path
into
file://\\somedrive\some\path
but if substrings already have a file:// then I don't want to append it again.
This doesn't seem to do anything:
var_export( str_replace( '\\\\', 'file://\\\\', '\\somedrive\some\path file://\\somedrive\some\path' ) );
What am I doing wrong? Also, the above doesn't take into test for file:// already being there; what's the best way of dealing with this?
UPDATE test input:
$test = '
file://\\someserver\some\path
\\someotherserver\path
';
test output:
file://\\someserver\some\path
file://\\someotherserver\path
Thanks.
You should consider escape sequence in string also.
if((strpos($YOUR_STR, '\\\\') !== false) && (strpos($YOUR_STR, 'file://\\\\') === false))
var_export( str_replace( '\\\\', 'file://\\\\', $YOUR_STR ) );
Use a regular expression to check if the given substring starts with file://. If it does, don't do anything. If it doesn't, append file:// at the beginning of the string:
if (!preg_match("~^file://~i", $str)) {
$str = 'file://' . $str;
}
As a function:
function convertPath($path) {
if (!preg_match("~^file://~i", $path)) {
return 'file://'.$path;
}
return $path;
}
Test cases:
echo convertPath('\\somedrive\some\path');
echo convertPath('file://\\somedrive\some\path');
Output:
file://\somedrive\some\path
file://\somedrive\some\path
EDIT
For multiple occurrences : preg_replace('#((?!file://))\\\\#', '$1file://\\\\', $path)
This will work to give you the output you are expecting. As php.net says double slash will be converted into single slash.
if (!preg_match('/^file:\/\//', $str)) {
$str = "file://\\".stripslashes(addslashes($str));
}
Please try this:
$string = "\\somedrive\some\path";
$string = "\\".$string;
echo str_replace( '\\\\', 'file://\\\\',$string);

Find exact string inside a string

I have two strings "Mures" and "Maramures". How can I build a search function that when someone searches for Mures it will return him only the posts that contain the "Mures" word and not the one that contain the "Maramures" word. I tried strstr until now but it does now work.
You can do this with regex, and surrounding the word with \b word boundary
preg_match("~\bMures\b~",$string)
example:
$string = 'Maramures';
if ( preg_match("~\bMures\b~",$string) )
echo "matched";
else
echo "no match";
Use preg_match function
if (preg_match("/\bMures\b/i", $string)) {
echo "OK.";
} else {
echo "KO.";
}
How do you check the result of strstr? Try this here:
$string = 'Maramures';
$search = 'Mures';
$contains = strstr(strtolower($string), strtolower($search)) !== false;
Maybe it's a dumb solution and there's a better one. But you can add spaces to the source and destination strings at the start and finish of the strings and then search for " Mures ". Easy to implement and no need to use any other functions :)
You can do various things:
search for ' Mures ' (spaces around)
search case sensitive (so 'mures' will be found in 'Maramures' but 'Mures' won't)
use a regular expression to search in the string ( 'word boundary + Mures + word boundary') -- have a look at this too: Php find string with regex
function containsString($needle, $tag_array){
foreach($tag_array as $tag){
if(strpos($tag,$needle) !== False){
echo $tag . " contains the string " . $needle . "<br />";
} else {
echo $tag . " does not contain the string " . $needle;
}
}
}
$tag_array = ['Mures','Maramures'];
$needle = 'Mures';
containsString($needle, $tag_array);
A function like this would work... Might not be as sexy as preg_match though.
The very simple way should be similar to this.
$stirng = 'Mures';
if (preg_match("/$string/", $text)) {
// Matched
} else {
// Not matched
}

how to return matches value using preg_replace()

please how do that ?
<?php
$string = '<inc="file.php">';
return preg_replace('#<inc\s*="\s*([a-zA-Z0-9\_]+)\">#',include("$1"),$string);
?>
the output is return $1
i need to return include file.php
If you have PHP 5.3 or higher:
<?php
$string = '<inc="file.php">';
return preg_replace_callback('#<inc\s*="\s*([a-zA-Z0-9\_]+)\">#', function($matches) {
return include $matches[1];
}, $string);
?>
I think it should be
return preg_replace('#<inc\s*="\s*([a-zA-Z0-9\_]+)\">#','include("'.$1.'")',$string);
The second parameter should be a string.
I'm not exactly sure what you're trying to do, but try using preg_match over preg_replace.
It gathers the matches into an array if you use it like shown:
preg_match('#<inc\s*="\s*([a-zA-Z0-9\_]+)\">#', $string, $matches);
And then the matches are stored in the $matches array. You can then loop over them using foreach.

Content Spinning using PHP?

Can anyone please help me? Say if I had this text or a smaller section stored in a variable, how can I randomise the words in the '{ }' ?
For example, the first one is "{important|essential|crucial|critical|vital|significant}" how can I make PHP choose one of those words randomly and then echo it? Thanks for helping me. :)
http://webarto.com/62/random-sentence-spinning-function
function get_random($matches)
{
$rand = array_rand($split = explode("|", $matches[1]));
return $split[$rand];
}
function show_randomized($str)
{
$new_str = preg_replace_callback('/\{([^{}]*)\}/im', "get_random", $str);
if ($new_str !== $str) $str = show_randomized($new_str);
return $str;
}
Applied on your text file... http://ideone.com/rkuf6
strip off initial and ending curly braces, you can use trim()
explode the resulting string on | using explode()
use array_rand() for the array you had in last step
Will not work with nested({a|x {b|c} y|z})!
function doStuff($from){
$to="";
while(($pos=strpos($from,'{'))!==false){
$to.=substr($from,0,$pos);
$from=substr($from,$pos);
$closepos=strpos($from,'}');
$arr=explode('|',substr($from,1,$closepos-1));
$to.=$arr[array_rand($arr)];
$from=substr($from,$closepos+1);
}
return $to.$from;
}

Categories